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

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

最简单的解决方案可能是使用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; } }