开发者

Aligning all panel components java

开发者 https://www.devze.com 2022-12-28 16:56 出处:网络
I am using the BoxLayout layout manager 开发者_如何学Goin java, and have aligned a bunch of components:

I am using the BoxLayout layout manager 开发者_如何学Goin java, and have aligned a bunch of components:

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?

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


setAlignmentX is defined in JComponent.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消