问题
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?
Here is my code:
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));
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.
回答2:
Add a Boolean field if you want checkbox in JTable.
False will be deselect and true value will represent selected checkbox.
You can find Boolean column type while adding a JTable if you are a NetBeans user.
For more check this SO que.
How to add JCheckBox in JTable?
来源:https://stackoverflow.com/questions/21050164/adding-jcheckbox-into-jtable