What is java.awt.Component.getName() and setName() used for?

Component.setName(..) is used in the JDK mostly by the look and feel implementation classes to set ID-like strings for each component, e.g. BasicOptionPaneUI might call it on a button component to set its name to "OptionPane.button".

The getName() is used in toString() methods, when setting the names of child components inside a Composite/parent Component and in AWT and Swing debug logging code. I suspect strongly that the getName() method is also used by some AWT/Swing testing frameworks.

So if you're not dependent on any of the above uses of getName(), you might try using it for your help messages, though I would not recommend it.

Maybe you should reconsider your design? Use the name to do some lookup in a hashmap that loads the help text from a resource bundle?


I haven't seen it used for anything by the framework. Its useful if you have components being passed in to a method so you can ask their name to decide how to handle them. Also, many UI testing frameworks use this to allow you to refer to the components by name in the testing scripts. I don't see any reason you can't use it for help text though.


Herman Lintvelt's answer ended up being the correct one for my app.

I created a resource bundle named HelpText.properties. It contains name=value pairs. I setName()d each of my Components with the "name" from the name=value pair. I then used a the frame's getGlassPane() to capture all mouse movements. When a mouse runs over a named component, it looks up the name in the bundle, displays help if available and forwards the mouse motion to along to the actual Component.

  • Look here for how to use the glass pane.
  • Jan Newmarch's web page on using resource bundles was very helpful.
  • Kevin Riff's response helped me figure out how to find my resource bundle.

Whew. Only 2 days worth of dinking around. I'm finally starting to get used to Java :)


FEST uses the name of a Component to identify it in testcases.