/**
*
*/
package de.tutorials;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridLayout;
import java.lang.reflect.Field;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* @author Tom
*
*/
public class ComponentIntrospectionExample extends JFrame {
JLabel lblA, lblB, lblC;
public ComponentIntrospectionExample() {
super("ComponentIntrospectionExample");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(1, 3));
lblA = new JLabel("A");
lblA.setName("A");
lblB = new JLabel("B");
lblB.setName("B");
lblC = new JLabel("C");
lblC.setName("C");
add(lblA);
add(lblB);
add(lblC);
pack();
setVisible(true);
System.out.println(getFieldNameForComponentWithName(
"B",
getContentPane()));
}
private Object getFieldNameForComponentWithName(
String componentName,
Container parentContainer) {
Component[] components = parentContainer.getComponents();
for (int i = 0; i < components.length; i++) {
Component component = components[i];
if (componentName.equals(component.getName())) {
Field[] fields = getClass().getDeclaredFields();
for (int j = 0; j < fields.length; j++) {
Field field = fields[j];
field.setAccessible(true);
try {
if (field.get(this) == component) {
return field.getName();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
return null;
}
/**
* @param args
*/
public static void main(String[] args) {
new ComponentIntrospectionExample();
}
}