Use Button as renderer for list

旧街凉风 提交于 2019-12-11 00:48:12

问题


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.

Minimal example

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


回答1:


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.



来源:https://stackoverflow.com/questions/11408971/use-button-as-renderer-for-list

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