Prakhar Singh Prakhar Singh - 1 year ago 70
Java Question

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");


class MyJFrame extends JFrame {
MyJPanel mjp;

public MyJFrame(String title) {

mjp = new MyJPanel();

Container ct = getContentPane();

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

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.

Answer Source

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) );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download