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?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With