Java Swing, Put Component In The Center

It has been quite some time since I used this :

Dimension SCREEN_SIZE = Toolkit.getDefaultToolkit().getScreenSize();
MainFrame mainFrame = new MainFrame();
int halfWidth = mainFrame.getWidth() / 2;
int halfHeight = mainFrame.getHeight() / 2;
mainFrame.setLocation(SCREEN_SIZE.width / 2 - halfWidth, SCREEN_SIZE.height / 2 - halfHeight);
mainFrame.setVisible(true);

Example for a Frame.

And apparently, you can use this one line instead:

mainFrame.setLocationRelativeTo(null); // or 'this' to parent

damn πŸ˜€

Advertisements

5 thoughts on “Java Swing, Put Component In The Center

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s