I'm using netbeans and i connect it with SQLite database, below you will find the code which i use to fill the jtable from the database, the problem is that the status column ((third column)) shows me the boolean value as 1s and 0s how can i make it as a jcheckboxs inside the jtable?
private void Update_table() {
try {
String sql = "select Name,location,Status from Items where E_ID =" +
Integer.parseInt(E_I.getText());
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
jtable1.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Now i use this but the checkboxs never get checked!! the color of the row is changed and the checkbox is appears at the column wich i want but the problem is how to make it checked if true!!
public class CheckBoxRenderer extends JCheckBox implements TableCellRenderer {
CheckBoxRenderer() {
setHorizontalAlignment(JLabel.CENTER);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setSelected(true);
} else {
setSelected(false);
}
return this;
}
}
public class MyCellRenderer extends javax.swing.table.DefaultTableCellRenderer {
public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table, java.lang.Object value, boolean isSelected, boolean hasFocus, int row, int column) {
final java.awt.Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
Object val = table.getValueAt(row, 2);
String sval = val.toString();
int ival = Integer.parseInt(sval);
if (ival == 0) {
cellComponent.setForeground(Color.black);
cellComponent.setBackground(Color.magenta);
} else {
cellComponent.setBackground(Color.white);
cellComponent.setForeground(Color.black);
}
if (isSelected) {
cellComponent.setForeground(table.getSelectionForeground());
cellComponent.setBackground(table.getSelectionBackground());
}
CheckBoxRenderer checkBoxRenderer = new CheckBoxRenderer();
Itabel.getColumnModel().getColumn(2).setCellRenderer(checkBoxRenderer);
return cellComponent;
}
}
Rendering is achieved through the use of a combination of look ups in the JTable
, keyed to a given Class
type and a TableCellRenderer
.
The JTable
will ask the TableModel
for the columnClass
and will look up a TableCellRenderer
to use for that given type.
By default, when TableModel#getColumnClass
method returns Boolean.class
, the JTable
will use a JCheckBox
to render the given value.
Take a look at How to Use Tables and SOLVED - setting the data of the next column in jtable in java for two examples