通过他们的id查找Swing组件?

时间:2011-02-17 18:05:17

标签: java swing

是否可以通过某种查找方法获取对swing对象的引用?为每个UI元素保留大量实例变量似乎是一种过度杀伤

即有点在javascript中完成的方式:

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

PS。我不是在为哥伦比亚号航天飞机编写软件。这是一个快速而肮脏的项目,因此最佳实践不适用。 THX。

1 个答案:

答案 0 :(得分:2)

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;

    }