简体   繁体   English

对齐所有面板组件Java

[英]Aligning all panel components java

I am using the BoxLayout layout manager in java, and have aligned a bunch of components: 我在Java中使用BoxLayout布局管理器,并对齐了许多组件:

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

I have a lot of components, and this seems over the top. 我有很多组件,这似乎很重要。 Is there a shorthand way? 有速记方法吗?

I tried the following, but setAlignmentX isn't a method inside Component? 我尝试了以下操作,但是setAlignmentX不是Component内部的方法吗?

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

setAlignmentX is defined in JComponent . setAlignmentXJComponent定义。

You could cast after checking: 您可以在检查后进行投射:

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

If you have nested your components, it might be necessary to make a recursive method out of that. 如果您嵌套了组件,则可能有必要从中创建一个递归方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM