How do I make a centered JFrame? - JAVA Interview Questions

How do I make a centered JFrame?


If you have a JFrame and you want to center the position in the screen you can use the following formula. Let's say you have a class called MainForm.



import java.awt.*;
import javax.swing.*;

public class MainForm extends JFrame
{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Get the size of our screen
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();

MainForm mainForm = new MainForm();
mainForm.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);

mainForm.setSize(250, 250);

// Calculates the position where the MainForm
// should be paced on the screen.
mainForm.setLocation((screenSize.width -
mainForm.getWidth()) / 2,
(screenSize.height -
mainForm.getHeight()) / 2);

mainForm.pack();
mainForm.setVisible(true);
}
});
}
}



Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

1 comments:

trustno1 said...

java programming examples to learn
Arrays of arrays samples

Related JAVA Questions Posts