将JCheckBox添加到JTable中 [英] Adding JCheckBox into JTable

查看:155
本文介绍了将JCheckBox添加到JTable中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序可以将数据库显示为动态JTable.它的工作正常.现在,我想在表的每个字段中添加1列,并添加CheckBox.我该怎么办?

I have a program to display database into a dynamic JTable. Its working fine. Now I want to add 1 more column into the table with CheckBox in each field. What should I do?

这是我的代码:

public static DefaultTableModel myTableModel(ResultSet rs) throws SQLException {
    ResultSetMetaData metadata = (ResultSetMetaData) rs.getMetaData();
    int columnsCount = metadata.getColumnCount();
    Vector<String> columnNames = new Vector<>();
    for (int i = 1; i < columnsCount; i++) {
        columnNames.add(metadata.getColumnName(i));
    }
    Vector<Object> data = new Vector<>();
    while (rs.next()) {
        Vector<Object> eachLine = new Vector<>();
        for (int i = 1; i < columnsCount; i++) {
            eachLine.add(rs.getObject(i));
        }
        data.add(eachLine);
    }
    return new DefaultTableModel(data, columnNames);
}

推荐答案

好的.我如何再添加1列?.

okay.how i can add 1 more column ?.

您需要为名称和添加到模型的每一行添加一列.要将列添加到表的开头,您可以执行以下操作:

You need to add a column for the name and for each row you add to the model. To add the columns at the beginning of the table you could do:

Vector<String> columnNames = new Vector<>();
columnNames.add("Boolean");
...
Vector<Object> data = new Vector<>();
data.add(new Boolean(false));

不需要创建自定义渲染器,但是正如其他人提到的那样,您需要重写getColumnClass()方法以为该列返回Boolean.class,以便表可以使用适当的渲染器.

There is no need to create a custom renderer, but as others have mentioned you need to override the getColumnClass() method to return Boolean.class for that column so the table can use the appropriate renderer.

这篇关于将JCheckBox添加到JTable中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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