如何使JTable列包含复选框? [英] How to make JTable column contain checkboxes?

查看:341
本文介绍了如何使JTable列包含复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前言:我对Java感到恐惧,而对Java ui组件则更糟.

Preface: I am horrible with java, and worse with java ui components.

我找到了一些有关如何向表添加按钮的不同教程,但是我在添加复选框方面很费力.我需要有一列来绘制一个默认选中的文本框(我认为可以处理单元格渲染器),然后单击该复选框,取消选中该框,重新绘制所述框,并在我可以跟踪的地方触发一个事件.

I have found several different tutorials on how to add buttons to tables, however I am struggling with adding checkboxes. I need to have a column that draws a text box ticked on default (cell renderer i think handles that), then on click of tickbox, unticks the box, redraws said box, and fires off an event somewhere I can track.

目前,我有一个自定义的cellrenderer:

currently I have a custom cellrenderer:

public class GraphButtonCellRenderer extends JCheckBox implements TableCellRenderer {
public GraphButtonCellRenderer() {
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    if(isSelected)
        setSelected(true);
    else
        setSelected(false);
    setMargin(new Insets(0, 16, 0, 0));
    setIconTextGap(0);

    setBackground(new Color(255,255,255,0));
    return this;
}}

当前处理绘制复选框,但是如果选中该行,则仅勾选和取消选中该复选框.但是我不知道该如何处理这些事件.确实,我要问的可能是有关如何将复选框干净地添加到JTable的优秀教程的链接. 非常感谢您的协助:)

Which currently handles drawing the tick box, but only ticks and unticks the box if that row is selected. But I don't know how to handle the events. Really what I am asking is possibly a link to a good tutorial on how to add checkboxes cleanly to a JTable. Any assist is greatly appreciated :)

推荐答案

无需创建自己的表渲染器. 这是一个更简单的示例.只需创建一个自定义表模型,并为给定的列返回Boolean类,即可:

There's no need to create your own table renderer. Here's a simpler example. Just create a custom table model and for a given column return the class Boolean for:

public Class getColumnClass(int column)

如果您希望列可编辑,请为true返回

If you want the column to be editable, return true for

public boolean isCellEditable(int row, int column)

JTable负责您的呈现.

JTable takes care of the rendering for you.

此处是另一个示例.

这篇关于如何使JTable列包含复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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