Wednesday, 20 May 2009

Centering a JFrame

The old way to center a JFrame was to use the default java.awt.Toolkit object and call getScreenSize then explicitly call setLocation on the JFrame.


Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int x = frame.getSize().width;
int y = frame.getSize().height;


Since 1.4 the better way is to call setLocationRelativeTo(null). This will center the JFrame. If you supply a Component object to the function, and the component is say on the left side of the screen, your JFrame will appear to the right of the screen.

No comments: