从组件数组中获取与 JPanel 组件关联的变量

问题描述 投票:0回答:1

假设我有一个 JPanel,其中包含按钮(和其他内容)作为组件,并且我创建了这些组件的数组:

JPanel panel = new JPanel();

JButton btn1 = new JButton();
JButton btn2 = new JButton();
JButton btn3 = new JButton();

panel.add(btn1);
panel.add(btn2);
panel.add(btn3);

Component[] things = panel.getComponents();`

如何获取与数组中的组件关联的变量名称?我正在寻找“btn1”、“btn2”等...

for (int i = 0; i < things.length; i++) {

*I need this to return the names of the variables associated with the components*

}
arrays swing components class-instance-variables
1个回答
0
投票

我用反射弄清楚了:

Field[] fields = panel.getClass().getDeclaredFields();
        for (Field f : fields) {
            if (f.getType().equals(JButton.class)) {
                System.out.println(f.getName());
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.