如何从具有GridBagLayout布局的JPanel获取位于特定gridx中的组件,gridy?

时间:2013-09-27 05:36:21

标签: java swing user-interface gridbaglayout

我有一个带有gridbaglayout布局的jpanel,其中有几个jtextfields,几个jlabels,几个动态添加的jbuttons。因此我无法知道他们的具体命令,因此无法使用panel.getComponent(count)。我查看api是否有像getGridx(int x)或getGridy(int y)这样的东西。没找到。有什么类似的方法吗?

1 个答案:

答案 0 :(得分:2)

最简单的解决方案可能是使用GridBagLayout#getConstraints(Component)并简单地循环遍历所有组件,直到找到与所需网格位置匹配的组件...

Component match = null;
GridBagLayout layout = ...
for (Component comp : getComponents()) {
    GridBagConstraints gbc = layout.getConstraints(comp);
    if (gbc.gridx = x && gbc.gridy = y) {
        match = comp;
        break;
    }
}
相关问题