2

Alright this may seem like a weird question but is there a way that after calling something like

jPanel3.getComponent(0).getName();

That I can use that value to make a call on a variable. Basically if it returns say jLabel1. That I can use that to call something on that label such as .setText("Hi"); Instead of having to type jLabel1.setText("hi"). Meaning can I use the returned value to directly call a function on it.

3 Answers 3

1

If I understood the question correctly, you want something like this:

Component c=jPanel3.getComponent(0);
if (c instanceof JLabel)
    ((JLabel)c).setText("hi");
Sign up to request clarification or add additional context in comments.

1 Comment

That was EXACTLY what I was looking for, thanks so much Jon, and thanks for the other suggestion Paulo
1

The name property of Components (i.e. getName() and setName()) have no relation to the variable which you once used when creating it. You can do this, for example (but don't, as this is very confusing):

Component textField1 = new JLabel("text");
textField1.setName("comboBox1");
System.out.println(textField1.getName()); // comboBox1

There is no way to get back to your textField1 name - the variable may not even exist anymore when you are calling the getName() method. You can even create (and use) components without ever using an explicit variable for them, like this:

panel.add(new JLabel("text"));

As written by Jon, you can cast the component to the real type, and don't need the name of the original variable.

Comments

0

You can do something like that when there is a panel as component available which is having two fields like label & textfields(It can be textfield & texfield).

Component[] components = panel.getComponents();
            for (Component component : components) {
                if (component instanceof JPanel) {
                    JPanel subPanel = (JPanel) component;
                    JLabel label = (JLabel) subPanel.getComponent(0);
                    JTextField textField = (JTextField) subPanel.getComponent(1);
                }
            }

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.