Search code examples
javaswingjframelayout-managerboxlayout

Using BoxLayout in JFrame


I am trying to use JFrame and BoxLayout to achieve a GUI similar to the one shown, but I am not sure how to center my Stop and Play buttons. Any suggestions?

enter image description here

Here is my code:

JFrame frame = new JFrame();

    Box box = Box.createHorizontalBox();
    box = Box.createHorizontalBox();
    box.add(new JButton("Play"));
    box.add(new JButton("Stop"));
    box.add(Box.createHorizontalGlue());
    frame.add(box, BorderLayout.SOUTH);

    frame.setSize(500, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setVisible(true); 

I have not yet coded in the text box and load button as I haven't yet been able to figure out centering.


Solution

  • Create a seperate panel for buttons. With horizontal glue you can center your buttons.

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
    
    buttonPanel.add(Box.createHorizontalGlue());
    
    buttonPanel.add(new JButton("Play"));
    buttonPanel.add(new JButton("Stop"));
    
    buttonPanel.add(Box.createHorizontalGlue());
    
    frame.add(buttonPanel, BorderLayout.SOUTH);
    

    Also you can do that with FlowLayout easily

    JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
    
    buttonPanel.add(new JButton("Play"));
    buttonPanel.add(new JButton("Stop"));
    
    frame.add(buttonPanel, BorderLayout.SOUTH);