Skip to content
Advertisement

Java Swing JButton alignment – BoxLayout

Below is a small example where two radio buttons are offset too far to the left column.

Radiobutton labels are incorrectly offset

However, if I remove the “A” button above by commenting out this code:

enter image description here

Then the 2 radio buttons are displayed as expected and not offset:

enter image description here

How do I get the radio buttons aligned correctly like the second case, but with the button present? Here is the code:

Main.java:

package layoutdemo;

import java.awt.Color;
import java.awt.Frame;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class Main extends JFrame {  
    public Main() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setExtendedState(Frame.MAXIMIZED_BOTH);
        getContentPane().setLayout(new BoxLayout(this.getContentPane(), BoxLayout.X_AXIS));
        getContentPane().setBackground(Color.black);
        add(new LeftPanel());
        pack();
        setVisible(true);
    }

    public static void main(String args[]) {
        new Main();
    }
}

LeftPanel.java:

package layoutdemo;

import java.awt.Component;
import java.awt.Dimension;

import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

public class LeftPanel extends JPanel {
    public LeftPanel() {
        this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        //add(new ButtonPanel());
        add(new JRadioButton("RadioBut2"));
        add(new JRadioButton("RadioBut1"));
    }

    @Override
    public Dimension getPreferredSize() {
        Component p = getParent();
        while(p.getParent() != null) {
            p = p.getParent();
        }
        Dimension dimension = p.getSize();
        return new Dimension(100, (int) (dimension.getHeight()));
    }
    
    @Override 
    public Dimension getMaximumSize() {
        return getPreferredSize();
    }
}

ButtonPanel.java:

package layoutdemo;

import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JPanel;
import javax.swing.JToggleButton;

public class ButtonPanel extends JPanel {
    public ButtonPanel() {
        add(new JToggleButton("A"));
    }
    
    @Override
    public Dimension getPreferredSize() {
        Component p = getParent();
        while(p.getParent() != null) {
            p = p.getParent();
        }
        Dimension dimension = p.getSize();
        return new Dimension(dimension.width, 50);
    }
    
    @Override 
    public Dimension getMaximumSize() {
        return getPreferredSize();
    }
}

Advertisement

Answer

It could be to do with the “alignmentX” property for those items. Trying setting all those items to the same alignmentX value.

enter image description here

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement