tags:

views:

85

answers:

4

As a followup to my question about the java.awt.Component.getName() property, I'm wondering if there is a way of squirreling an arbitrary object somewhere in a Component, similar to the tag property in .NET? This would be really handy for any code that does work to a component but doesn't necessarily know what that component is.

For example, say I'm trying to implement an application-wide help system that knows to look at any component currently pointed to by the mouse, reach into that component and pull out it's help text and display it in it's own pane on the screen (no, I don't want to use a tooltip). My answer currently is to use the Name (getName()/setName()) to store the help text, and this will work, but the Name has to be a string. If I wanted to get fancier and store anything other than a string, I think I'd be stuck.

+1  A: 

Component doesn't have a way to do this. However, one option would be to use a static map and provide a wrapper around it so you can query for data relating to any UI (or other) object. I've done this sort of thing before and as long as you set it up as a kind of service with interfaces, it can be pretty elegant and doesn't break your OO design.

AdamC
A: 

Yeah, you could use the get/setName to set some kind of identifier, then use that identifier for mapping to your help. the JavaHelp CSH stuff works kind of like that, except that i believe that is putting the component itself into a map?

John Gardner
+1  A: 

I generally create a hash and put (component, cookie) whenever I add a component to the screen. When you need your cookie object back (in an event perhaps), the event always gets a copy of the component, and then you are just a get(component) away from your cookie.

In some extreme conditions, I've subclassed the control and just added a field. It's a quick and dirty fix since subclassing the component is just like a few lines of code and can go in the same class the file where you are generating your screen. This is only useful if you just need to store your data connected to a single type of control.

Bill K
+2  A: 

JComponent has putClientProperty and getClientProperty.

Tom Hawtin - tackline