jTable 布尔列显示 true/false 而不是复选框

jTable boolean column shows true/false instead of checkboxes

我正在创建一个 netbeans java 项目,用于从 Microsoft Access 数据库中检索数据。 我需要为我的其中一个列显示一个可编辑的复选框,但由于某种原因,它显示为 true/false。设计视图中的 jTable 显示复选框,但当我 运行 时显示程序 true/false。 虽然我已经尝试过,但我真的不了解编辑器和渲染器,没有这个的解决方案会更可取,但如果这是唯一的方法,请解释如何去做。

这是我的 GUI 代码:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package timetable;



/**
 *
 * @author Lenovo
 */
public class TaskFrame extends javax.swing.JFrame {

    /**
     * Creates new form Main
     */
    public TaskFrame() {
        initComponents();
        this.setLocationRelativeTo(null);
        
        taskList t = new taskList()
        jtblTodayTasks.setModel(t.filljtblTodayTasks());
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtblTodayTasks = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(255, 255, 255));
        setMinimumSize(new java.awt.Dimension(1100, 619));
        setResizable(false);
        setSize(new java.awt.Dimension(1100, 619));
        getContentPane().setLayout(null);


        jtblTodayTasks.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
        jtblTodayTasks.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "ID", "Task", "Subject", "Due Date", "Completed"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jtblTodayTasks);
        if (jtblTodayTasks.getColumnModel().getColumnCount() > 0) {
            jtblTodayTasks.getColumnModel().getColumn(4).setPreferredWidth(0);
        }
        

        pack();
    }// </editor-fold>                            

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        //</editor-fold>

        //</editor-fold>

        //</editor-fold>

        /* Create and display the form */
        
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TaskFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jtblTodayTasks;
    private javax.swing.JTabbedPane tabbedPane;
    // End of variables declaration                   
}

这是我的任务列表class:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package timetable;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Lenovo
 */
public class taskList {
    ArrayList<Task> taskArray = new ArrayList<>();
    
    public taskList(){
        ConnectDB db = new ConnectDB();
        ResultSet rs = db.getResults("SELECT * FROM tblTasks WHERE userID = " + Login.currentUserID + " ORDER BY dueDate;");
        
        try{
            while (rs.next()){
                Task task = new Task(rs.getInt("taskID"), rs.getInt("userID"), rs.getString("taskName"), rs.getString("Subject"), rs.getString("taskDetails"), rs.getString("dueDate"), rs.getBoolean("Completed"));
                taskArray.add(task);
            }
            rs.close();
        }catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "Database error. Please contact the system Administrator");
        }
    }
    
    public DefaultTableModel filljtblTodayTasks(){
        
        Object[] columnNames = {"ID", "Task", "Subject", "Due Date", "Completed"};
        DefaultTableModel model = new DefaultTableModel(columnNames, 0);
        
        for (int i = 0; i < taskArray.size(); i++) {
            model.addRow(new Object[]{taskArray.get(i).getTaskID(), taskArray.get(i).getTaskName(), taskArray.get(i).getSubject(), taskArray.get(i).getDueDate(), taskArray.get(i).isCompleted()});
        }
        return model;
    }

非常感谢!

The jTable in the Design view shows checkboxes but when I run the program true/false is displayed.

getColumnClass(...) 方法确定每列使用哪个渲染器

您的 TaskFrame 中的代码已经创建了自定义模型并覆盖了 getColumnClass(...) 方法。

但是你创建了另一个 table 模型但没有覆盖 getColumnClass(...) 方法:

    Object[] columnNames = {"ID", "Task", "Subject", "Due Date", "Completed"};
    DefaultTableModel model = new DefaultTableModel(columnNames, 0);

不要创建新的 DefaultTableModel。

相反,您可以使用:

DefaultTableModel model = (DefaultTableModel)jtblTodayTasks.getModel();
model.setRowCount( 0 );

以上代码将从现有模型中删除数据,因此您可以添加新数据。