Why an object is called using Swing BoxLayout

Can someone explain why the text “Options” is missing here? It 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); } } 
+4
source share
2 answers

The problem is that JLabel aligns the right edge with the center of the panel, and scrolling aligns its center with the center of the panel.

I was able to fix this by adding two lines, setting the horizontal alignment of both label and jscrlpBox to Component.LEFT_ALIGNMENT :

 JLabel label = new JLabel("Option"); label.setAlignmentX(Component.LEFT_ALIGNMENT); // Added 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); jscrlpBox.setAlignmentX(Component.LEFT_ALIGNMENT); // Added 

In general, when troubleshooting issues like this, I try to add a brightly colored line border to components (in this case label ) that are not where I want them. This is when I realized that he aligned the right edge with the same line as the other component to align its center.

+4
source

Read the section in the Swing tutorial on Using Window Layout . There are several examples that try to explain how the "alignment by X" of each component can affect the layout.

If you describe what you are trying to do, or what you expect, perhaps we can suggest using a different combination of layout managers.

+2
source

Source: https://habr.com/ru/post/1301987/


All Articles