[英]Adding JCheckBox into JTable
I have a program to display database into a dynamic JTable
. 我有一个程序可以将数据库显示到动态
JTable
。 Its working fine. 它的工作正常。 Now I want to add 1 more column into the table with CheckBox in each field.
现在,我想在表的每个字段中添加1列,并添加CheckBox。 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);
}
okay.how i can add 1 more column ?.
好的,我如何再增加1列?
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. 无需创建自定义渲染器,但是正如其他人提到的那样,您需要重写getColumnClass()方法以为该列返回Boolean.class,以便表可以使用适当的渲染器。
Add a Boolean
field if you want checkbox in JTable
. 如果需要,请在
JTable
添加一个Boolean
字段。 False will be deselect and true value will represent selected checkbox. False将被取消选择,true值将代表选中的复选框。 You can find
Boolean
column type while adding a JTable
if you are a NetBeans user. 如果您是NetBeans用户,则在添加
JTable
时可以找到Boolean
列类型。
For more check this SO que. 有关更多信息,请查看此que。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.