如何在Java Swing中创建带有复选框的列表? [英] How do I make a list with checkboxes in Java Swing?

查看:803
本文介绍了如何在Java Swing中创建带有复选框的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java Swing中有一个带有复选框的项目列表的最佳方法是什么?

What would be the best way to have a list of items with a checkbox each in Java Swing?

I.e。带有一些文本和每个复选框的项目的JList?

I.e. a JList with items that have some text and a checkbox each?

推荐答案

创建自定义 ListCellRenderer 并将其指定为 JList

Create a custom ListCellRenderer and asign it to the JList.

此自定义 ListCellRenderer 必须在 getListCellRendererComponent(...)方法的实现中返回 JCheckbox

This custom ListCellRenderer must return a JCheckbox in the implementantion of getListCellRendererComponent(...) method.

但是这个 JCheckbox 将无法编辑,屏幕上的简单画面由你来选择,当这个 JCheckbox 必须勾选或不勾选,

But this JCheckbox will not be editable, is a simple paint in the screen is up to you to choose when this JCheckbox must be 'ticked' or not,

例如,在选择行时显示勾选(参数 isSelected ),但这样一来,如果选择改变,检查状态将不会被保留。最好显示它检查 ListModel 下面的数据,但是由您来实现更改数据检查状态的方法,并通知更改为要重新绘制 JList

For example, show it ticked when the row is selected (parameter isSelected), but this way the check status will no be mantained if the selection changes. Its better to show it checked consulting the data below the ListModel, but then is up to you to implement the method who changes the check status of the data, and notify the change to the JList to be repainted.

如果需要,我会稍后发布示例代码

I Will post sample code later if you need it

ListCellRenderer

这篇关于如何在Java Swing中创建带有复选框的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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