使用结果集添加动态JCheckBox

问题描述 投票:0回答:1

我看到这个Need to add JCheckBox In JTable Dynamically,但它没有任何帮助,看到我的情况类似,但我不知道如何从我的数据库中取出原始数据后添加JCheckBox

    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);
    }
}

这就是视图的样子

java swing jtable jcheckbox defaulttablemodel
1个回答
0
投票

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

您不添加JCheckBox。 TableModel保存数据,而不是组件。所以你需要:

  1. 覆盖TableModel的getColumnClass(...)方法,为要复选框的列返回Boolean.class。然后该表将使用正确的渲染器/编辑器作为复选框。
  2. 从ResultSet添加数据时,将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);

当然,您还需要将“行”数组放大以保持此值。

© www.soinside.com 2019 - 2024. All rights reserved.