How do I make a centered JFrame?
Category: javax.swing, viewed: 2830 time(s).
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.
package org.kodejava.examples.javax.swing;
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);
}
});
}
}
|