【问题标题】:Making button in JList clickable使 JList 中的按钮可点击
【发布时间】:2014-04-29 09:58:58
【问题描述】:

我不敢相信这不起作用。

我有一个 JList。我已将其渲染器设置如下。基本上RankingPanel 是一个带有两个标签和一个按钮的 JPanel。

topAchieverList = new JList();
topAchieverList.setCellRenderer(new TopBottomCellRenderer());

这是我的 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;
    }
}

列表正确呈现,但JButton 不可点击。点击它什么都不做。

我该如何进行这项工作?

【问题讨论】:

    标签: java swing jbutton jlist


    【解决方案1】:

    渲染器只是涂在组件上的“橡皮图章”。它们不是实时的交互式组件。

    请参阅此答案:JButton in JList 以获得一种可能的解决方案。实际上,您将MouseListener 添加到您的JList,确定在该点击点呈现哪个特定按钮,然后以编程方式点击该按钮。

    或者,您可以制作一个JPanel 按钮,并将面板放在JScrollPane 中。

    或者,您可以创建一个单列 JTable,您可以在其中实现自定义 TableCellEditor,如下所示:Table Button Column

    【讨论】:

    • 所以基本上不可能。有一些“骇人听闻”的方法可以迫使它发生......我最终将我所有的RankingPanel 对象添加到了JPanel,我将其添加到了“JScrollPane”中。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2015-09-26
    • 2021-02-09
    相关资源
    最近更新 更多