Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing - JList custom cell rendering - capturing actions

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?

like image 278
Evan Fosmark Avatar asked Apr 13 '09 03:04

Evan Fosmark


2 Answers

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.

like image 148
Peter Walser Avatar answered Oct 21 '22 20:10

Peter Walser


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).

like image 36
Neil Coffey Avatar answered Oct 21 '22 20:10

Neil Coffey