对齐所有面板组件ja​​va

时间:2010-05-02 11:05:43

标签: java swing user-interface alignment

我在java中使用BoxLayout布局管理器,并且已经对齐了许多组件:

myLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
myTextBox.setAlignmentX(Component.LEFT_ALIGNMENT);
myButton.setAlignmentX(Component.LEFT_ALIGNMENT);
...

我有很多组件,这似乎超过顶部。有简写方法吗?

我尝试了以下方法,但是setAlignmentX不是Component中的方法吗?

for (Component c : personPanel.getComponents()) {
    c.setAlignmentX(Component.LEFT_ALIGNMENT);
}

1 个答案:

答案 0 :(得分:3)

setAlignmentXJComponent中定义。

你可以在检查后施放:

for (Component c : personPanel.getComponents()) {
    if(c instanceof JComponent) {
        ((JComponent)c).setAlignmentX(Component.LEFT_ALIGNMENT);
    }
}

如果嵌套了组件,则可能需要使用递归方法。