Java: Any way of squirreling an object about a Component somewhere in the Component?

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.

Asked by: Robert617 | Posted: 28-01-2022

Answer 1

JComponent has putClientProperty and getClientProperty.

Answered by: David323 | Posted: 01-03-2022

Answer 2

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.

Answered by: Sophia983 | Posted: 01-03-2022

Answer 3

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.

Answered by: Brad306 | Posted: 01-03-2022

Answer 4

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?

Answered by: Daniel109 | Posted: 01-03-2022

Similar questions

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)