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

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

问题描述

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

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

即一个 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天全站免登陆