Saideira
Saideira

Reputation: 2414

looking up Swing components by their id?

Is it possible to get a reference to a swing object via some lookup method ??

Keeping a multitude of instance variables for every single UI element seems to be such an overkill

ie kinda the way its done in javascript:

JTextArea ta = new JTextArea();
ta.setId("myJTextArea");
....
....
....
JTextArea ta = window.getElementById("myJTextArea");
ta.setTexT("blah");

PS. I'm not writing software for space shuttle columbia. This is a quick and dirty projects, so best practices dont apply. Thx.

Upvotes: 0

Views: 5946

Answers (1)

Bala R
Bala R

Reputation: 108957

private static Component getComponentById(Container container, String componentId){

        if(container.getComponents().length > 0)
        {
            for(Component c : container.getComponents())
            {
                if(componentId.equals(c.getName()))
                {
                    return c;
                }
                if(c instanceof Container)
                {
                    return getComponent((Container) c, componentId);
                }
            }
        }

        return null;

    }

Upvotes: 2

Related Questions