简体   繁体   English

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

[英]jTable boolean column shows true/false instead of checkboxes

I am creating a.netbeans java project that retrieves data from a microsoft access database.我正在创建一个 .netbeans java 项目,该项目从 Microsoft Access 数据库中检索数据。 I need to display an editable checkbox for one of my columns but for some reason it comes up as true/false instead.我需要为我的其中一个列显示一个可编辑的复选框,但由于某种原因,它显示为 true/false。 The jTable in the Design view shows checkboxes but when I run the program true/false is displayed.设计视图中的 jTable 显示复选框,但当我运行程序时,会显示 true/false。 I really don't understand editors and renders though I have tried, a solution without this would be preferable but if it is the only way, please explain how to do it.尽管我已经尝试过,但我真的不了解编辑器和渲染器,没有这个的解决方案会更好,但如果这是唯一的方法,请解释如何去做。

Here is my GUI code:这是我的 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                   
}

Here is my taskList class:这是我的任务列表 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;
    }

Thank you so much!太感谢了!

The jTable in the Design view shows checkboxes but when I run the program true/false is displayed.设计视图中的 jTable 显示复选框,但当我运行程序时,会显示 true/false。

The getColumnClass(...) method determines which renderer is used for each column getColumnClass(...)方法确定每个列使用哪个渲染器

The code in your TaskFrame already creates a custom model and overrides the getColumnClass(...) method. TaskFrame 中的代码已经创建了自定义 model 并覆盖了getColumnClass(...)方法。

But then you create another table model but are not overriding the getColumnClass(...) method:但是随后您创建了另一个表 model 但没有覆盖getColumnClass(...)方法:

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

Don't create a new DefaultTableModel.不要创建新的 DefaultTableModel。

Instead you can just use:相反,您可以使用:

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

The above code will remove the data from the existing model, so you can add new data.上面的代码将从现有的 model 中删除数据,因此您可以添加新数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM