I can't believe this does not work.
I have a JList. I have set its renderer as follows. Basically RankingPanel
is a JPanel with two labels and a button.
topAchieverList = new JList();
topAchieverList.setCellRenderer(new TopBottomCellRenderer());
Here is my TopBottomCellRenderer.
class TopBottomCellRenderer extends RankingPanel implements ListCellRenderer {
public TopBottomCellRenderer() {
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
try {
Achievers achiever = (Achievers) value;
if (achiever == null) {
return this;
}
itemRank.setText("#" + achiever.rank);
itemUnits.setText("" + achiever.units);
//this is the button that does not click
itemNameButton.setText(achiever.name);
//set bg
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
return this;
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
}
The list renders properly but the JButton
is not clickable. Clicking it does nothing.
How do I make this work?
Renderers are just "rubber stamps" painted onto the component. They are not live, interactive components.
See this answer: JButton in JList for one possible solution. Effectively, you add a MouseListener
to your JList
, determine which particular button is being rendered at that click-point, then programmatically click that button.
Or, you could make a JPanel
of buttons, and place the panel in a JScrollPane
.
Or, you could make a single-column JTable
, where you could implement a custom TableCellEditor, as seen here: Table Button Column