有人可以解释为什么“选项”文本在这里缩进吗?这看起来像是 BoxLayout 中的错误。时间差
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);
}
}
最佳答案
这里的问题是 JLabel 将其右边缘与面板中心对齐,而滚动 Pane 将其中心与面板中心对齐。
我能够通过添加两行来解决这个问题,将 label
和 jscrlpBox
的水平对齐设置为 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
一般来说,在对此类问题进行故障排除时,我会尝试向组件(在本例中为 label
)添加颜色鲜艳的边框,但这些边框不是我想要的。就在那时,我意识到它正在将其右边缘与其他组件用于对齐其中心的同一条线对齐。
关于java - 为什么使用 Swing BoxLayout 缩进对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2308097/