How to add checkbox in Jtable populated using rs2x

2019-03-02 18:31发布

问题:

I don't know how to go about i have this frame i wish to populate a JTable and add a checkbox.

public static void update_table() {

        try {

        String sql="SELECT * FROM equipments";
        PreparedStatement update = con.prepareStatement(sql);
        ResultSet result = update.executeQuery();
        table.setModel(DbUtils.resultSetToTableModel(result));
        table.setVisible(true);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

回答1:

I assume you mean to want to add an additional column not found in the database containing a check box so you can select rows?

If so then you can use a wrapper TableModel.

Here is an untested example that might help:

public class CheckBoxWrapperTableModel extends AbstractTableModel
{
    private Map<Integer, Boolean> checkBoxes = new HashMap<Integer, Boolean>();

    private TableModel model;
    private String columnName;

    public CheckBoxWrapperTableModel(TableModel model, String columnName)
    {
        this.model = model;
        this.columnName = columnName;
    }

    @Override
    public String getColumnName(int col)
    {
        return (column > 0) ? model.getColumnName(col - 1) : columnName;
    }

    @Override
    public int getRowCount()
    {
        return model.getRowCount();
    }

    @Override
    public int getColumnCount()
    {
        return model.getColumnCount() + 1;
    }

    @Override
    public Object getValueAt(int row, int col)
    {
        if (col > 0)
            return model.getValueAt(row, col - 1);
        else
        {
            Object value = checkBoxes.get(row);
            return (value == null) ? Boolean.FALSE : value;
        }
    }

    @Override
    public boolean isCellEditable(int row, int col)
    {
        if (col > 0)
            return model.isCellEditable(row, col - 1);
        else
            return true;
    }

    @Override
    public void setValueAt(Object value, int row, int col)
    {
        if (col > 0)
            model.setValue(value, row, col - 1);
        else
            checkBoxes.put(row, value);

        fireTableCellUpdated(row, col);
    }

    @Override
    public Class getColumnClass(int col)
    {
        return (col > 0) ? model.getColumnClass(col - 1) : Boolean.class;
    }
}

If the model works then you would us the model with code like:

//table.setModel(DbUtils.resultSetToTableModel(result));
TableModel utilsModel = DbUtils.resultSetToTableModel(result);
TableModel wrapperModel = new CheckBoxWrapperTableModel(utilsModel, "Select");
table.setModel( wrapperModel );