Making button in JList clickable
Asked Answered
P

1

8

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?

Possing answered 21/3, 2014 at 20:25 Comment(0)
T
7

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

Thousandth answered 21/3, 2014 at 20:36 Comment(1)
So basically its not possible. There are "hackish" ways to force it to happen... I ended up adding all my RankingPanel objects to a JPanel which i added to a `JScrollPane'. Thanks for the help.Possing

© 2022 - 2024 — McMap. All rights reserved.