Reputation:
I want to add a checkbox to the JTable, when the database value is true or false (currently I am using Oracle database, so its not accepting boolean type).
When the value is true, the checkbox will be shown selected/checked.
Everything is fine, but the JTable displayed like true and false.
Here is my code:
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);
}
Upvotes: 1
Views: 1450
Reputation: 3752
First of all your data will need to be objects not strings, something like
Object[] data = new Object[columnNames.length];
then add your value from the database
data[0] = new Boolean(rs.getBoolean(0));
then set up your default renderer for the column in question
table.getColumnModel().getColumn(0).setCellRenderer(
new MyCellRenderer());
and here is the renderer
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());
}
}
Upvotes: 1