Making button in JList clickable

岁酱吖の 提交于 2020-07-03 06:09:29

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/22568849/making-button-in-jlist-clickable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!