如何从SQLite中检索数据时在jTable中创建jCheckbox

时间:2014-05-01 20:36:03

标签: java sqlite netbeans jtable jcheckbox

我使用netbeans并将其与SQLite数据库连接,下面你会发现我用来从数据库中填充jtable的代码,问题是状态列((第三列))显示了我布尔值为1和0如何将其作为jtable中的jcheckbox?

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);
    }
}

现在我使用这个,但复选框永远不会被检查!!行的颜色被更改,复选框出现在我想要的列,但问题是如何检查是否为真!!

    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;

        }

         }

1 个答案:

答案 0 :(得分:1)

通过使用JTable中的查找组合,键入给定的Class类型和TableCellRenderer来实现渲染。

JTable会向TableModel询问columnClass,并会查找TableCellRenderer以用于该指定类型。

默认情况下,当TableModel#getColumnClass方法返回Boolean.class时,JTable将使用JCheckBox呈现给定值。

有两个例子,请查看How to Use TablesSOLVED - setting the data of the next column in jtable in java