Creating two buttons at bottom left/right corner

前端 未结 4 1120
梦谈多话
梦谈多话 2021-01-26 03:09
JButton button1 = new JButton(\"Button 1\");
JButton button2 = new JButton(\"Button 2\");
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new BorderLayout(         


        
4条回答
  •  隐瞒了意图╮
    2021-01-26 03:38

    You might want to consider using BoxLayout's horizontalGlue:

    import java.awt.BorderLayout;
    
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    
    public class ButtonsLeftAndRight {
        private JFrame frame;
        private JPanel pane;
        private JButton button1;
        private JButton button2;
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new ButtonsLeftAndRight()::createAndShowGui);
        }
    
        public void createAndShowGui() {
            frame = new JFrame(getClass().getSimpleName());
    
            pane = new JPanel();
            pane.setLayout(new BoxLayout(pane, BoxLayout.LINE_AXIS));
    
            button1 = new JButton("Button1");
            button2 = new JButton("Button2");
    
            pane.add(button1);
            pane.add(Box.createHorizontalGlue());
            pane.add(button2);
    
            frame.add(pane, BorderLayout.SOUTH);
    
            frame.pack();
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    }
    

    This might get you this, before and after resizing:

提交回复
热议问题