How to set the initial size of a Java JFrame

I've been getting back into the Java/Swing world during the last few days, and I thought I'd share some example code here. In my current application, one of the things I just worked on was setting the initial JFrame size to a value I liked.

At least on my MacBook Pro, I found that setting the initial JFrame height and width to 2/3 of the corresponding screen dimensions was pretty nice. Here's some example Java code that shows how I set the height and width to 2/3 of the screen dimensions:

// get the screen size as a java dimension
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

// get 2/3 of the height, and 2/3 of the width
int height = screenSize.height * 2 / 3;
int width = screenSize.width * 2 / 3;

// set the jframe height and width
jframe.setPreferredSize(new Dimension(width, height));

As you can see, setting the initial JFrame size is very straightforward. I think a ratio of 2/3 is probably going to be way too large on my 24" iMac, but on my much smaller MacBook Pro it is a good initial JFrame size.

JFrame, Dimension, and Toolkit javadoc

As a closing note, here are a few links to the Java classes used in this example: