2010-05-02 41 views
1

我使用Java中的BoxLayout布局管理器,并对准一堆组件:对齐所有面板组件的java

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

我有很多组件,这似乎在上面。有速记方式吗?

我试过以下,但setAlignmentX不是组件内的方法?

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

回答

3

setAlignmentX定义在JComponent中。

检查后,您可以施放:

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

如果你嵌套了您的组件,可能需要做一个递归方法了这一点。