I am having a small problem of showing results from my database to a JTable. It displays all of the data correctly, but at the moment it is showing "true" or "false" for boolean.
I know it must be because I am using getString
, but does anyone know what to use in order to change it to a checkbox instead?
Current JTable:
My Database:
Code:
connection con=new connection();
Connection getcon=null;
Vector col = new Vector();
Vector dat= new Vector();
ResultSet rs = null;
try{
getcon = con.creatConnection();
col.add("Fanta");
col.add("Crisps");
col.add("Beer");
col.add("Wine");// create income table default colum names and sore it
col.add("Water");
col.add("Seat Row");
col.add("Seat");
col.add("Total Cost");
rs=getcon.createStatement().executeQuery("select*from orders"); //getting all the information from the table
dat.clear();
while(rs.next()){// if record source avilable
Vector v =new Vector();
v.add(rs.getString("Fanta").trim());
v.add(rs.getString("Crisps").trim());
v.add(rs.getString("Beer").trim());
v.add(rs.getString("Wine").trim());// getting income values from database and store in dat
v.add(rs.getString("Water").trim());
v.add(rs.getString("SeatRow").trim());
v.add(rs.getString("Seat").trim());
v.add(rs.getString("TotalCost").trim());
dat.add(v);
}
orderResults.setModel(new DefaultTableModel(dat, col));
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
First you have to save data as a Boolean in your model. So you should use this rs.getBoolean("Fanta")
instead of rs.getString("Fanta").trim()
.
Second, you have to override a public Class getColumnClass(int column)
method from your JTable
. Your code could look like this:
JTable orderResults = new JTable() {
@Override
public Class getColumnClass(int column) {
// first 5 columns will be represented as an checkbox
if(column <= 4){
return Boolean.class;
}
// rest of them as a text
return String.class;
}
};