Get a Swing component by name

I know this is an old question, but I found myself asking it just now. I wanted an easy way to get components by name so I didn’t have to write some convoluted code each time to access different components. For example, having a JButton access the text in a text field or a selection in a List.

The easiest solution is to make all of the component variables be class variables so that you can access them anywhere. However, not everyone wants to do that, and some (like myself) are using GUI Editors that don’t generate the components as class variables.

My solution is simple, I’d like to think, and doesn’t really violate any programming standards, as far as I know (referencing what fortran was getting at). It allows for an easy and straightforward way to access components by name.

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

    private HashMap componentMap;
    
  2. 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();
    }
    
  3. 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;
    }
    
  4. Now you’ve got a HashMap that maps all the currently existing components in your frame/content pane/panel/etc to their respective names.

  5. 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.

If you plan on adding, removing, or renaming components at any point during runtime, I would consider adding methods that modify the HashMap according to your changes.

Leave a Comment