MrG MrG - 10 months ago 55
Java Question

Java JFrame: howto parse recursively through componets (i.e. if using JScrollPane)

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)
return found;

Unfortunately I ran into issues after using using
to support scrolling in
and JTable's, which I did with:

JTextArea ta = new JTextArea();
JScrollPane scr = new JScrollPane(ta);
frame.getContentPane().add(scr, "1, 1"); // EDIT: changed, tkx bruno

After suggestions, I've been able to access through
the desired component (the version above is the final one). Many thanks to Dan and Bruno!

Answer Source

@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:

void printNames(Component component) {
    for (Component child : component.getComponents()) {

void printFrameNamesComponents(JFrame frame) {

(not tested, but something like this.)