Can someone explain why the text “Options” is indented here? This looks like a bug to me in BoxLayout. TIA
import javax.swing.*;
import java.awt.*;
public class BoxLayoutIssue {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(240, 250);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JLabel label = new JLabel("Option");
panel.add(label);
JLabel a = new JLabel("A");
JLabel b = new JLabel("B");
JLabel c = new JLabel("C");
JLabel d = new JLabel("D");
JLabel e = new JLabel("E");
Box box = Box.createVerticalBox();
box.add(a);
box.add(b);
box.add(c);
box.add(d);
box.add(e);
JScrollPane jscrlpBox = new JScrollPane(box);
jscrlpBox.setPreferredSize(new Dimension(140, 90));
panel.add(jscrlpBox);
f.add(panel);
f.setVisible(true);
}
}
The issue here is that the JLabel is lining up its right edge with the center of the panel, while the scrollpane is lining up its center with the center of the panel.
I was able to fix this by adding two lines, setting the horizontal alignment of both
labelandjscrlpBoxtoComponent.LEFT_ALIGNMENT:In general, when troubleshooting something like this, I try adding a brightly colored line border to the components (in this case,
label) that aren’t where I want them to be. That’s when I realized that it was lining up its right edge with the same line that the other component was using for lining up its center.