Reputation: 35
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.
Upvotes: 2
Views: 16332
Reputation: 84
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);
}
}
Upvotes: 0
Reputation: 74750
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.
Upvotes: 1
Reputation: 13738
If I understood the question correctly, you want something like this:
Component c=jPanel3.getComponent(0);
if (c instanceof JLabel)
((JLabel)c).setText("hi");
Upvotes: 1