使JList中的按钮可单击 [英] Making button in JList clickable

查看:70
本文介绍了使JList中的按钮可单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法相信这是行不通的.

I can't believe this does not work.

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

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());

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

列表将正确显示,但JButton不可单击.单击它无济于事.

The list renders properly but the JButton is not clickable. Clicking it does nothing.

我如何进行这项工作?

推荐答案

渲染器只是在组件上绘制的橡皮图章".它们不是实时的交互式组件.

Renderers are just "rubber stamps" painted onto the component. They are not live, interactive components.

查看此答案: JList中的JButton 一种可能的解决方案.实际上,您可以在JList中添加一个MouseListener,确定在该点击点上呈现的是哪个特定按钮,然后以编程方式单击该按钮.

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.

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

Or, you could make a JPanel of buttons, and place the panel in a JScrollPane.

或者,您可以制作一个单列JTable,在其中可以实现自定义TableCellEditor,如下所示:

Or, you could make a single-column JTable, where you could implement a custom TableCellEditor, as seen here: Table Button Column

这篇关于使JList中的按钮可单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆