Tell me how to make JFrame located in the center, and not in the upper left corner, as in the screenshot:

enter image description here

final int h = 600; final int w = 600; QScreen screen = new QScreen(w, h, 24); JFrame f = new JFrame(); f.setResizable(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLocationRelativeTo(null); f.add(screen); f.setTitle("Example"); f.setSize(w, h); f.setVisible(true); 

    1 answer 1

    JFrame by default uses BorderLayout , which stretches components to all available space. The easiest way, I think, is to take java.awt.GridBagLayout , like this:

     // ... // f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); GridBagConstraints gbc = new GridBagConstraints( 0, 0, // x, y в сетке 1, 1, // ширина и высота в сетке 0, 0, // веса GridBagConstraints.CENTER, // привязка внутри занятого места в сетке GridBagConstraints.NONE, // растяжение new Insets(0, 0, 0, 0), // отступы от границ компонента до границ места в сетке 0, 0 // внутренние отступы (компонент займет не меньше минимального размера + отступ ); f.setLayout( new GridBagLayout() ); f.add(screen, gbc); f.setTitle("Example"); // ... //