使用Button作为列表的渲染器 [英] Use Button as renderer for list

查看:96
本文介绍了使用Button作为列表的渲染器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用更复杂的渲染器,该渲染器由几个组件组成,用于列表(更准确地说是

I would like to use a more complex renderer consisting of several components for a list (more precisely something like this (a textfieldinput with some buttons arranged in a panel). However when I try to use a button in a list it seems to ignore clicks.

最小示例

from javax.swing import DefaultListCellRenderer
from javax.swing import DefaultListSelectionModel
from javax.swing import JButton
from javax.swing import JLabel
from javax.swing import JPanel
from javax.swing import JList
from javax.swing import JFrame


def printer():
    print "pressed the button"

class cellRenderer(DefaultListCellRenderer):



    def getListCellRendererComponent(self, theList, value, index, selected, hasFocus):
        renderer = DefaultListCellRenderer.getListCellRendererComponent(self, theList, value, index, selected, hasFocus)

        if selected:
            pan = JPanel()
            pan.add(JLabel('beer'))
            pan.add(JButton('get one', actionPerformed=printer))
            renderer = pan

        return renderer

panel = JFrame('example', size=(200,200))

configurations = JList([1,2,3,4],
                       cellRenderer = cellRenderer(),
                       selectionMode = DefaultListSelectionModel.SINGLE_SELECTION )

panel.add(configurations)
panel.visible = True

编辑:根据建议添加了最小示例.更新问题,因为在最少的示例创建过程中解决了原始问题

edit:added minimal example as suggested. Updated question since original problem was solved during minimal example creation

推荐答案

仅渲染器是不够的.您还需要一个不属于JList API的编辑器.或者,将JTable与自定义渲染器和编辑器一起使用. JRadioAsRendererEditor 是添加包含单选按钮的StatusPanel的示例.当然,您也可以使用多列表也是如此.

A renderer alone is not sufficient; you also need an editor, which is not part of the JList API. As an alternative, use a JTable with a custom renderer and editor. JRadioAsRendererEditor is an example that adds a StatusPanel containing radio buttons. Of course, you can also use a multi-column table, too.

这篇关于使用Button作为列表的渲染器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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