使用结果集添加动态JCheckBox

时间:2018-09-09 10:34:16

标签: java swing jtable jcheckbox defaulttablemodel

我看到了这个Need to add JCheckBox In JTable Dynamically,但是看到我的情况相似却无济于事,但是我不确定从数据库中获取原始数据后如何添加JCheckBox。 / p>

    public void fillAnyTable(ResultSet resultSet, JTable table)throws SQLException{

        //Create new table model
        DefaultTableModel tableModel = new DefaultTableModel();

        //Retrieve meta data from ResultSet
        ResultSetMetaData metaData = resultSet.getMetaData();

        //Get number of columns from metadata
        int columnCount = metaData.getColumnCount();

        //Get all column names from metadata and add columns to table
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++){
            tableModel.addColumn(metaData.getColumnLabel(columnIndex));
        }
        //this is when I assume I can create a new column but now how to add the checkbox
        tableModel.addColumn("Check");
        //Create Array of Objects with size of Column count from metadata
        Object[] row = new Object[columnCount];

        //Scroll through Result Set
        while (resultSet.next()){
            //Get object from column with specific index of result set to array of objects
            for (int i = 0; i < columnCount; i++){
                row[i] = resultSet.getObject(i+1);

            }
            System.out.println(Arrays.toString(row));
            //Now add row to table model with that array of objects as an argument
            tableModel.addRow(row);
        }
        //Now we add the table model to the table
        table.setModel(tableModel);
    }
}

这是视图的样子

This is what the view looks like

1 个答案:

答案 0 :(得分:0)

  

从数据库中获取原始数据后,我不确定如何添加JCheckBox。

您没有添加JCheckBox。 TableModel保存数据,而不保存组件。因此,您需要:

  1. 重写TableModel的getColumnClass(...)方法,以为要复选框所在的列返回Boolean.class。然后表格将使用正确的渲染器/编辑器作为复选框。

  2. 当您从ResultSet中添加数据时,
  3. 将Boolean.FALSE添加到TableModel中。

因此,在将每个列值添加到行数组中后,只需添加布尔值即可:

//Now add row to table model with that array of objects as an argument
row[columnCount].add( Boolean.FALSE );
tableModel.addRow(row);

当然,您还需要将“行”数组变大以容纳该值。