How do I make a centered JFrame?
Category: javax.swing, viewed: 7234 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);
}
});
}
}
Download Hundreds of Complimentary Industry Resources
Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more;
all available at no cost to you. With more than 600 complimentary offers, you'll find
plenty of titles to suit your professional interests and needs.
Click Here and Sign up today!