2010-05-02 58 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); 
    } 
} 

如果你嵌套了您的組件,可能需要做一個遞歸方法了這一點。