Java Swing - JList custom cell rendering - capturing actions
Asked Answered
A

2

6

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?

Alchemize answered 13/4, 2009 at 3:25 Comment(2)
Very good question. I thought it might have something to do with ItemListeners, but now I don't think so... I tried finding sample code but wasn't successful.Chronic
Hi, I facing the same problem, are you able to solve the problem?Nickell
M
6

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

Mesmerize answered 13/4, 2009 at 4:42 Comment(0)
B
11

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.

Banerjee answered 14/4, 2009 at 8:2 Comment(1)
Think of the rendered component as a rubber stamp.Schechter
M
6

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

Mesmerize answered 13/4, 2009 at 4:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.