Search code examples
javaswingjpanellayout-managerboxlayout

BoxLayout.Y_AXIS not working in Swings


import javax.swing.*;
import java.awt.*;

class MyJPanel extends JPanel {
JButton login, register;

public MyJPanel() {
    login = new JButton("Login");
    register = new JButton("Register");

    this.add(register);
    this.add(login);
}
}

class MyJFrame extends JFrame {
MyJPanel mjp;

public MyJFrame(String title) {
    super(title);

    mjp = new MyJPanel();

    Container ct = getContentPane();
    ct.add(mjp);


    setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
    setSize(400,400);
    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
}
}

class Gui7FirstPage {
public static void main(String[] args) {
    MyJFrame mjf = new MyJFrame("Welcome!");
}
}

The above code is aligning the 2 Buttons Login and Register along X-Axis. I intend to stack them up using BoxLayout.Y_AXIS but it doesn't seem to work.

The 2 buttons are aligned horizontally side by side and I want them to be place verically.


Solution

  • By default a JPanel uses a FlowLayout, so your MyJPanel class is using a FlowLayout.

    You are adding your buttons to the panel, so the panel needs to use the BoxLayout, NOT the content pane.

    At the start of the constructor for your class you need:

    setLayout( new BoxLayout(this, BoxLayout.Y_AXIS) );