views:

257

answers:

3

I have a class that contains a JButton. This can't be changed.

The problem is this: The actionListener calls getSource() and gets the JButton, not the container class.

Can I change what getSource retrieves, before the actionListener is added? OR can JButtons have a variable reference to its container?

I can't make a class extend a JButton. It caused bugs for drawing purposes... story of my week.

+1  A: 

See JButton.getParent()

Chuk Lee
The object it is contained in isn't a Component, it just stored a JButton object, along with other data.getParent therefore won't return the Object that contains the JButton.Any other way you know to have a button reference something, or to override the JButton's ActionListener functinos, that provide a "source"?
Brandon
How about setting the name (setName) or the actionCommand (setActionCommand). Then use that to retrieve the container from a globally accessible map?
Chuk Lee
+1  A: 

It is much better to add context to the listener than to use getSource.

Tom Hawtin - tackline
+1  A: 

For attaching arbitrary data to any JComponent, use [putClientProperty(Object key, Object value)][1], then in your listener, call getClientProperty(Object key) to retrieve the value.

[1]: http://java.sun.com/javase/6/docs/api/javax/swing/JComponent.html#putClientProperty(java.lang.Object, java.lang.Object)

Devon_C_Miller