Java Swing - Creating Custom JList Cells - Capturing Actions

Whenever I create my own cell renderer for JList, any elements that I add to it never respond to actions. For example, if I have a cell renderer, I return a JPanel with elements on it, one of which has an ActionListener, it does not respond at all.

Why is this?

+6
java swing jlist
source share
2 answers

The element that you return as a means of displaying the list cells is designed for exactly that: rendering . Register listeners with a JList (usually you need a ListSelectionListener).

+6
source share

The renderer may look like a factory for returning components for cells, but in fact it follows lightweight rendering and uses the same component to render all the cells (each call to getListCellRendererComponent() should reconfigure the same component instance for a particular cell and return it so that you can display the cell).

That way you can have a JList (as well as JTable and JTree ) display a huge number of cells without having to create components for each cell. As a side effect, the visualization component cannot respond to events, since it is used only during the rendering cycle, but is not displayed in the component tree.

Just as Neil Coffey said, you can add your listeners to the JList ( JTable , JTree ) and use helper methods ( locationToIndex(...) , getCellBounds(...) ) to send this cell and therefore deal with specific cell logic.

+11
source share

All Articles