I’m using TableLayout for my swing GUI. Initially only some basic labels, buttons and text fields where required which I could later on access by:
public Component getComponent(String componentName) { return getComponent(componentName, this.frame.getContentPane()); } private Component getComponent(String componentName, Component component) { Component found = null; if (component.getName() != null && component.getName().equals(componentName)) { found = component; } else { for (Component child : ((Container) component).getComponents()) { found = getComponent(componentName, child); if (found != null) break; } } return found; }
Unfortunately I ran into issues after using using JScrollPane to support scrolling in JTextArea and JTable’s, which I did with:
JTextArea ta = new JTextArea(); ta.setName('fooburg'); JScrollPane scr = new JScrollPane(ta); frame.getContentPane().add(scr, '1, 1'); // EDIT: changed, tkx bruno
After suggestions, I’ve been able to access through getComponent('fooburg') the desired component (the version above is the final one). Many thanks to Dan and Bruno!
@bruno is right – you need to add the text pane to the frame’s content pane.
Slightly OT: If you generally want to access every component in a hierarchy, you need something recursive – your current method will only print immediate child names:
(not tested, but something like this.)