0

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*

}
2
  • 1
    Why do you think you need the variable name of each button. Sounds like a design problem to me. Commented Jan 3, 2024 at 15:09
  • It may very well be a design problem, though it may not. I'm trying to implement a user interface with formatted JPanels. The panels already have JButtons and I'm trying to create a method that will assign certain actions to certain buttons (in the main method), or also create buttons and assign actions to the buttons when the JPanel is instantiated. This is a perplexing problem. Commented Jan 16, 2024 at 17:25

1 Answer 1

1

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());
            }
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.