Reputation: 59
I want to insert JCheckBox
in every row in JTable
so I try to change my first column type. When I try this code, I get "java.lang.String cannot be cast to java.lang.Boolean" error.
DefaultTableModel model=new DefaultTableModel(){
private static final long serialVersionUID = 1L;
@Override
public Class<?> getColumnClass(int column) {
switch (column) {
case 0:
return Boolean.class;
case 1:
return String.class;
case 2:
return String.class;
case 3:
return String.class;
default:
return String.class;
}
}
}
Upvotes: 4
Views: 6391
Reputation: 59
static String[] columnNames={"Name","Surname","Boolean"};
static Object[][] data={ {null,null,null };
JTable table=new JTable(data,columnNames);
public static void RESULTS(){
try{
rs=stm.executeQuery(sql);
Object[] row=new Object[2];
DefaultTableModel model=new DefaultTableModel(){
private static final long serialVersionUID = 1L;
@Override
public Class<?> getColumnClass(int column) {
switch (column) {
case 2: return Boolean.class;
default: return String.class;
}
}
};
table.setModel(model);
model.setColumnIdentifiers(columNames);
while (rs.next()){
for (int v=1;v<3;v++){
if(v==2){ row[2]=false; // or true..
}
else{ row[v-1]=rs.getObject(v); }
}
model.addRow(row);
}//while
rs.close();
}//try
catch (SQLException e) { System.out.println(e); }
}
I did that, it works
Upvotes: 2
Reputation: 205875
Be certain to add values of type Boolean.class
to your TableModel
, as shown here. See also Creating a Table Model for a typical implementation.
@Override
public Class<?> getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
Addendum: I changed row value as true
.
There are several ways to ensure that the model contains a value of type Boolean.class
:
Boolean.TRUE
or Boolean.FLASE
, constants defined in java.lang.Boolean
.
Boolean.valueOf(boolean b)
, where b
may be a value or expression yielding boolean
.
As @kleopatra notes, the simple tutorial implementation fails to meet two essential critera:
Guard against null
values.
Return the same value for the lifetime of the model.
Upvotes: 1