My question is how to access the Swing GUI element tree (main window, JPanels, JFrames, JButtons, JTextFields ect) and create a reference to that tree. I need this to be kept in a data structure (ex. hash map) and NOT in a memory file (eg. using serialization). I need this for using it later to map these UI elements to the corresponding objects inside the code.
EDIT:
JFrame f = new JFrame("Basic GUI");
JPanel pnl1 = new JPanel();
JPanel pnl2 = new JPanel();
JPanel pnl3 = new JPanel();
JLabel lblText = new JLabel("Test Label");
JButton btn1 = new JButton("Button");
JTextField txtField = new JTextField(20);
public GUISample(){
pnl1.add(lblText);
pnl2.add(btn1);
pnl3.add(txtField);
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(pnl2, BorderLayout.EAST);
f.getContentPane().add(pnl3, BorderLayout.WEST);
f.getContentPane().add(pnl1, BorderLayout.NORTH);
visitComponent(f);
}
private Map<String, Component> hashMap = new HashMap<String,Component>();
public Map<String, Component> getComponentsTree(){
return hashMap;
}
public void visitComponent(Component cmp){
// Add this component
if(cmp != null) hashMap.put(cmp.getName(), cmp);
Container container = (Container) cmp;
if(container == null ) {
// Not a container, return
return;
}
// Go visit and add all children
for(Component subComponent : container.getComponents()){
visitComponent(subComponent);
}
System.out.println(hashMap);
}