I need to be able to have a list of components in a class and their respective variable name. I did manage to get the list of all the components in the GUI. However when I call the getName method for the component, a null is being returned. Does anyone know how to be able to get such a name for a component please?
This is the code so far:
public static void main(String[] args){
Calculator c = new Calculator();
List<Component> containers = getAllComponents(c.getContentPane());
for (int i = 0; i < containers.size(); i++) {
System.out.println(containers.get(i).getClass().getName());
System.out.println(containers.get(i).getName());
}
System.exit(0);
}
public static List<Component> getAllComponents(final Container c) {
Component[] comps = c.getComponents();
List<Component> compList = new ArrayList<Component>();
for (Component comp : comps) {
compList.add(comp);
if (comp instanceof Container) {
compList.addAll(getAllComponents((Container) comp));
}
}
return compList;
}
getName()will only return a value if you calledsetName()before. But that name is arbitrary. It’s a debugging aid for UI developers.My guess is that you want to know which component is in which field of the
Calculatorclass. For this, you need to use the Reflection API.Try
Calculator.class.getDeclaredFields(). To read the value of a private field, see this example code.