如何在Java中获取GUI组件的名称?

时间:2012-03-16 09:53:42

标签: java user-interface

我需要能够在类中包含组件列表及其各自的变量名称。我确实设法获得GUI中所有组件的列表。但是,当我为组件调用getName方法时,返回null。有谁知道如何能够获得组件的这样名称?

这是到目前为止的代码:

public static void main(String[] args){
    Calculator c = new Calculator();

    List<Component> containers = getAllComponents(c.getContentPane());
    for (int i = 0; i < containers.size(); i++) {
        System.out.println(containers.get(i).getClass().getName());
        System.out.println(containers.get(i).getName());
    }
    System.exit(0);
}

public static List<Component> getAllComponents(final Container c) {
    Component[] comps = c.getComponents();
    List<Component> compList = new ArrayList<Component>();
    for (Component comp : comps) {
        compList.add(comp);
        if (comp instanceof Container) {
            compList.addAll(getAllComponents((Container) comp));
        }
    }
    return compList;
}

3 个答案:

答案 0 :(得分:1)

组件的getName()方法无法保证返回值,当然也不会返回组件分配的变量名称。另请注意,有几个变量可能指向同一个对象实例,因此即使信息可用,信息也不会有用。

答案 1 :(得分:1)

getName()只会在您之前调用setName()时返回一个值。但这个名字是任意的。它是UI开发人员的调试辅助工具。

我的猜测是你想知道哪个组件在Calculator类的哪个字段中。为此,您需要使用Reflection API

试试Calculator.class.getDeclaredFields()。要阅读私有字段的值,请参阅this example code

答案 2 :(得分:0)

每个组件都可以有一个名称,可以通过getName()和setName()访问,但是你必须编写自己的查找函数。

您也可以尝试使用HashMap。我找到了一个例子。

    Create a Map class variable. You'll need to import HashMap at the very least. I named mine componentMap for simplicity.

private HashMap componentMap;

    Add all of your components to the frame as normal.

initialize() {
    //add your components and be sure
    //to name them.
    ...
    //after adding all the components,
    //call this method we're about to create.
    createComponentMap();
}

    Define the following two methods in your class. You'll need to import Component if you haven't already:

private void createComponentMap() {
        componentMap = new HashMap<String,Component>();
        Component[] components = yourForm.getContentPane().getComponents();
        for (int i=0; i < components.length; i++) {
                componentMap.put(components[i].getName(), components[i]);
        }
}

public Component getComponentByName(String name) {
        if (componentMap.containsKey(name)) {
                return (Component) componentMap.get(name);
        }
        else return null;
}

    Now you've got a HashMap that maps all the currently existing components in your frame/content pane/panel/etc to their respective names.

    To now access these components, it is as simple as a call to getComponentByName(String name). If a component with that name exists, it will return that component. If not, it returns null. It is your responsibility to cast the component to the proper type. I suggest using instanceof to be sure.