我在 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);
}
最佳答案
setAlignmentX
在 JComponent
中定义.
您可以在检查后转换:
for (Component c : personPanel.getComponents()) {
if(c instanceof JComponent) {
((JComponent)c).setAlignmentX(Component.LEFT_ALIGNMENT);
}
}
如果您嵌套了组件,则可能需要从中创建一个递归方法。
关于java - 对齐所有面板组件java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2753243/