Search code examples
javamysqlswingjtablejcheckbox

Fill jtable from database and convert tinyint to checkbox in java


How i can fetch data from MySQL to JTable and add JTable column number 3 checkbox This is my code

String sql = "select `id`,`CostCentersName`, case when `Status` = 1 then true else false end AS Status from costcenters limit 0,10 ";
    Clas.classtable obj = new Clas.classtable();
    DefaultTableModel dtm = obj.Query(sql);
    datatable.setModel(dtm);
    CheckBoxRenderer checkBoxRenderer = new CheckBoxRenderer();
    datatable.getColumnModel().getColumn(2).setCellRen  derer(checkBoxRenderer);

And i see this error

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
at test.CheckBoxRenderer.getTableCellRendererComponent(CheckBoxRenderer.java:28)

and this is my class

public class CheckBoxRenderer extends JCheckBox implements TableCellRenderer {


public CheckBoxRenderer() {
    JCheckBox checkBox = new JCheckBox();
    setHorizontalAlignment(JLabel.CENTER);
        checkBox.setHorizontalAlignment(SwingConstants.CENTER);
        checkBox.setBackground( Color.blue);
    }
public static final DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer();

public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column) {
    Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);


    if (isSelected) {
        setForeground(table.getSelectionForeground());
        super.setBackground(table.getSelectionBackground());
        setBackground(table.getSelectionBackground());
        return c;
    } else {
        setForeground(table.getForeground());
        setBackground(table.getBackground());          
    }
   setSelected((value != null && ((Boolean) value).booleanValue())); 
    
    return this;
    }
 }

who can help mee?


Solution

  • finally i fix this

    Inside the class

    setSelected((value != null && ((Boolean) value).booleanValue()));
    

    It should be replaced

    setSelected(value != null && (Boolean.valueOf(value.toString()).booleanValue()));
    

    github