JFrame centered on screen Example
This JFrame example displays a JFrame with a panel containing labels. It uses the JFrame.setLocationRelativeTo() method, with a null parameter to get the default of the JFrame centered on the screen.
// JFrame centered on screen
import javax.swing.*;
class JFrameCenteredScreen {
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();
jframe.setLocationRelativeTo(null);
jframe.setVisible(true);
}
}
