【发布时间】:2014-09-17 06:49:56
【问题描述】:
我有一个带有 BoxLayout 管理器的 JPanel,其中包含子面板。我希望这些子面板中的组件具有左对齐,但它们总是居中显示。 看起来 BoxLayout 正确对齐了直接插入的组件,但当它们位于子面板内时却无法做到这一点。
我已经修改了http://www.java2s.com/Tutorial/Java/0240__Swing/YAxisAlignment.htm 中的示例,因此每个按钮都放置在子面板中,然后使用 BoxLayout 管理器将子面板放置在主面板中:
public class YAxisAlignX {
private static Container makeIt(String title, float alignment) {
String labels[] = { "--", "----", "--------", "------------" };
JPanel container = new JPanel();
container.setBorder(BorderFactory.createTitledBorder(title));
BoxLayout layout = new BoxLayout(container, BoxLayout.Y_AXIS);
container.setLayout(layout);
// modified loop. the original version does not create JPanel pan.
// adds the buttons directly the the JPanel container with the
// BoxLayout
for (int i = 0, n = labels.length; i < n; i++) {
JPanel pan = new JPanel();
JButton button = new JButton(labels[i]);
pan.add(button);
button.setAlignmentX(alignment);
pan.setAlignmentX(alignment);
container.add(pan);
}
return container;
}
public static void main(String args[]) {
JFrame frame = new JFrame("Alignment Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container panel1 = makeIt("Left", Component.LEFT_ALIGNMENT);
Container panel2 = makeIt("Center", Component.CENTER_ALIGNMENT);
Container panel3 = makeIt("Right", Component.RIGHT_ALIGNMENT);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(panel1);
contentPane.add(panel2);
contentPane.add(panel3);
frame.pack();
frame.setVisible(true);
}
}
如果执行此版本,您可以看到按钮都居中,尽管设置了对齐方式。为什么会这样?有什么解决办法吗?在我的例子中,每个子面板都包含几个组件,我不想直接添加到主面板中。
非常感谢。
【问题讨论】:
标签: java swing alignment layout-manager boxlayout