How to get component located in a specific gridx, gridy from a JPanel with GridBagLayout layout?

人盡茶涼 提交于 2020-01-11 10:43:11

问题


I have a jpanel with gridbaglayout layout, in it i have several jtextfields, several jlabels, several jbuttons which get added dynamically. Therefore I cannot know their specific orders, hence cannot use panel.getComponent(count). I looked in the api if there is something like getGridx(int x) or getGridy(int y). Didn't find. Is there anything similar to those methods?


回答1:


The simplest solution might be to use GridBagLayout#getConstraints(Component) and simply loop through all the components until you find one that matches the required grid position...

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


来源:https://stackoverflow.com/questions/19043373/how-to-get-component-located-in-a-specific-gridx-gridy-from-a-jpanel-with-gridb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!