Mr. Mutant
Mr. Mutant

Reputation: 11

Get the variable associated with a JPanel component from a component array

Say I have a JPanel with buttons (and other things) as components and I make an array of those components as such:

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();`

How can I get the names of the variables associated with the components in the array? I'm looking to grab "btn1", "btn2", etc...

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

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

}

Upvotes: 0

Views: 25

Answers (1)

Mr. Mutant
Mr. Mutant

Reputation: 11

I figured it out using reflection:

Field[] fields = panel.getClass().getDeclaredFields();
        for (Field f : fields) {
            if (f.getType().equals(JButton.class)) {
                System.out.println(f.getName());
            }
        }

Upvotes: 0

Related Questions