JFrame ScreenSize Example
This JFrame example, shown here running in the Introduction to Java Programming system, displays a JFrame with a panel containing labels.It uses the Toolkit class to get information about the screen size.
The JFrame is then able to be centered on the screen.
The example indicated below shows a simpler method of doing this.
// JFrame ScreenSize Example
import java.awt.*;
import javax.swing.*;
class JFrameScreenSize {
public static void main(String[] args) {
JFrame jframe = new JFrame("Desserts");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box b = new Box(BoxLayout.Y_AXIS);
b.add(new JLabel("Jelly"));
b.add(new JLabel("Baklava"));
b.add(new JLabel("Tiramisu"));
b.add(new JLabel("Pavlova"));
b.add(new JLabel("Kulfi"));
jframe.setContentPane(b);
jframe.pack();
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = jframe.getSize();
int x = (screenSize.width - frameSize.width) / 2;
int y = (screenSize.height - frameSize.height) / 2;
jframe.setLocation(x, y);
jframe.setVisible(true);
}
}
