views:

1419

answers:

3

Any time I make a custom cell renderer for a JList, any elements I add to it don't ever respond to actions. For instance, If I have the cell renderer return a JPanel with elements on it, one of which has an ActionListener, it doesn't respond at all.

Why is this?

+4  A: 

The item you return as a list cell renderer is intended for exactly that: rendering. Register listeners with the JList (generally, you'll want a ListSelectionListener).

Neil Coffey
+5  A: 

The renderer may look like a factory for returning components for the cells, but in fact it follows the flyweight rendering approach and uses the same component for rendering all the cells (each call to getListCellRendererComponent() is supposed to reconfigure the same component instance for a specific cell and return it so that cell can be rendered).

That way, you can have JList (as well as JTable and JTree) display massive amount of cells without having to instanciate components for each cell. As a side effect, the render component cannot respond to events, as it is only used during the render loop, but doesn't appear in the component tree.

Just as Neil Coffey said, you can add your listeners to the JList (JTable, JTree) instead, and use the helper methods (locationToIndex(...), getCellBounds(...)) to dispatch which cell was affected and thus deal with cell specific logic.

Peter Walser
+1 for a decent explanation
basszero
Think of the rendered component as a rubber stamp.
Daniel Schneller
A: 

10x guys ./. it helped me