Reputation: 3
I want a Jtable having three columns where two columns is selected from Database and third column need to have JcheckBoxes for each rows
I have a code like this
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columns);
table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
TableColumn tc = table.getColumnModel().getColumn(2);
tc.setCellEditor(table.getDefaultEditor(Boolean.class));
tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
frame.getContentPane().add(scroll);
String col_1 = "";
Integer col_2 = 0;
try
{
////DefaultTableModel default_model = new DefaultTableModel();
////default_model.setColumnIdentifiers(columns);
((DefaultTableModel) model).setColumnIdentifiers(columns);
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hdb","root","root");
Statement stmnt = con.createStatement();
java.sql.ResultSet rs=stmnt.executeQuery("select col_1,col_2 from databaseTable");
while(rs.next())
{
act_name = rs.getString("col_1");
time_in_min = rs.getInt("col_2");
model.addRow(new Object[]{col_1,col_2,new Boolean(false)});
//////((DefaultTableModel) model).addRow(new Object[]{col_1,col_2, Boolean.FALSE});
}
con.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
It just gives the column with false value not the checkboxes
Upvotes: 0
Views: 58
Reputation: 18792
Override to return the right column class
class MyTableModel extends DefaultTableModel{
public Class<?> getColumnClass(int columnIndex) {
return getValueAt(0, columnIndex).getClass();
}
}
And use it as your table model.
These lines
TableColumn tc = table.getColumnModel().getColumn(2);
tc.setCellEditor(table.getDefaultEditor(Boolean.class));
tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
will not be needed.
Upvotes: 1