BorderLayout center command won't center

后端 未结 3 1809
时光说笑
时光说笑 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:24

    Unintuitive as it seems, it is behaving correctly.

    panel1 is assigned as much screen space as is available, because it is the only component inside panel2. FlowLayout then lays out components starting from the top of the available space, and only puts components further down once it has filled all the horizontal space available. Thus, you get your two buttons at the top of the frame.

    You could try using a Box instead:

    public class test extends JFrame {
    
        private JComponent box = Box.createHorizontalBox();
        private JButton button1 = new JButton("one"); 
        private JButton button2 = new JButton("two"); 
    
        public test() {
            box.add(Box.createHorizontalGlue());
            box.add(button1);
            box.add(button2);
            box.add(Box.createHorizontalGlue());
            this.add(box);
        }
    
        ...
    }
    

    A horizontal box automatically centers components vertically, and the two glue components take up any extra horizontal space available so that the buttons sit in the center of the box.

提交回复
热议问题