我想在JTable中添加一个复选框,当数据库值为true或false时(目前我正在使用Oracle数据库,因此它不接受布尔类型)。
当值为true时,将显示选中/选中复选框。
一切都很好,但JTable显示为真假。
这是我的代码:
private void loadData(){
try {
con = Connection_Config.ConnectDB();
String sql = "select * from t_module_list";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
tab.setModel(buildTableModel(rs));
} catch (SQLException ex) {
}
}
public static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
/* for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}*/
columnNames.add("MODULE NAME");
columnNames.add("SUB_MODULE NAME");
columnNames.add("ADD");
columnNames.add("MODIFY");
columnNames.add("DELETE");
columnNames.add("VIEW");
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
System.out.println("rs.getObject(columnIndex)======="+rs.getObject(columnInde x));
if (rs.getObject(columnIndex).equals("false") ||
rs.getObject(columnIndex).equals("true")) {
vector.add(new Boolean(true));
} else {
vector.add(rs.getObject(columnIndex));
}
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
答案 0 :(得分:1)
首先,您的数据需要是对象而不是字符串,例如
Object[] data = new Object[columnNames.length];
然后从数据库中添加您的值
data[0] = new Boolean(rs.getBoolean(0));
然后为相关列设置默认渲染器
table.getColumnModel().getColumn(0).setCellRenderer(
new MyCellRenderer());
这里是渲染器
public class MyCellRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
if (value instanceof JComboBox) {
return (JComboBox) value;
}
if (value instanceof Boolean) {
JCheckBox cb = new JCheckBox();
cb.setSelected(((Boolean) value).booleanValue());
return cb;
}
if (value instanceof JCheckBox) {
return (JCheckBox) value;
}
return new JTextField(value.toString());
}
}