简体   繁体   English

使JList中的按钮可单击

[英]Making button in JList clickable

I can't believe this does not work. 我不敢相信这不起作用。

I have a JList. 我有一个JList。 I have set its renderer as follows. 我已将其渲染器设置如下。 Basically RankingPanel is a JPanel with two labels and a button. 基本上, RankingPanel是一个带有两个标签和一个按钮的JPanel。

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

Here is my 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;
    }
}

The list renders properly but the JButton is not clickable. 列表正确呈现,但JButton不可点击。 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. 请参阅此答案: JList中的JButton是一种可能的解决方案。 Effectively, you add a MouseListener to your JList , determine which particular button is being rendered at that click-point, then programmatically click that button. 实际上,您将一个MouseListener添加到JList ,确定在该单击点处呈现哪个特定按钮,然后以编程方式单击该按钮。

Or, you could make a JPanel of buttons, and place the panel in a JScrollPane . 或者,您可以创建按钮的JPanel ,并将面板放在JScrollPane

Or, you could make a single-column JTable , where you could implement a custom TableCellEditor, as seen here: Table Button Column 或者,您可以创建一个单列JTable ,您可以在其中实现自定义TableCellEditor,如下所示: 表按钮列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM