How can I center JButton? They do it like this, nothing happens:

import java.awt.*; import javax.swing.*; class GraphTest { public static void main(String[] args) { JFrame frame = new JFrame(" Hello!"); frame.setSize(new Dimension(300, 300)); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setLayout(new BorderLayout()); JPanel panel = new JPanel(); panel.setSize(new Dimension(100, 100)); panel.setBackground(Color.DARK_GRAY); JButton button = new JButton("Click me!"); button.setPreferredSize(new Dimension(100, 50)); panel.add(button); frame.add(panel, BorderLayout.CENTER); //не работает frame.setVisible(true); } } 

    1 answer 1

     import java.awt.*; import javax.swing.*; class GraphTest { public static void main(String[] args) { JFrame frame = new JFrame(" Hello!"); frame.setSize(new Dimension(300, 300)); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setResizable(false); Container c = frame.getContentPane(); c.setLayout(new BorderLayout()); JButton button = new JButton("Кнопка"); JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = GridBagConstraints.RELATIVE; panel.add(button, gbc); c.add(panel, BorderLayout.CENTER); frame.setVisible(true); } }