BorderLayout center command won't center

后端 未结 3 1888
时光说笑
时光说笑 2021-01-21 18:08

I am trying to place two JButtons next to each other in the center of a JFrame, that won\'t re-size the buttons when the JFrame is re-size

3条回答
  •  星月不相逢
    2021-01-21 18:36

    JPanel uses FlowLayout by default, and FlowLayout uses centered alignment by default... This seems easier to me than going to GridBagLayout or even BoxLayout. If you don't want the buttons to 'wrap' when the panel gets too small for them, you could set a minimum size.

    package example;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class FlowLO extends JFrame
    {
        public static void main(String[] args)
        {
            FlowLO flowLO = new FlowLO();
            flowLO.go();
        }
        public void go()
        {
            JPanel centeredPanel = new JPanel();
            centeredPanel.add(new JButton("one"));
            centeredPanel.add(new JButton("two"));
            getContentPane().add(centeredPanel);
            pack();
            setVisible(true);
        }
    }
    

提交回复
热议问题