views:

1106

answers:

2

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;
}

Unfotunately 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!

+1  A: 

You need to add the child to the JFrame's content pane instead:

frame.getContentPane().add(comp);

If you add your new component to JFrame directly, your code above never get's to it because you are only enumerating the components under frame.getContentPane().

bruno conde
tkx bruno, I changed the code as you suggested
MrG
+1  A: 

@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) {
    System.out.println(component.getName());
    for (Component child : component.getComponents()) {
        printNames(child);
    }
}

void printFrameNamesComponents(JFrame frame) {
    printNames(frame.getContentPane());
}

(not tested, but something like this.)

Dan Vinton
MrG