mercredi 29 juillet 2020

Listener for checkboxes in two different JTables

I am creating a java GUI in netbeans that has two tables. I made a listener for the JTables that will detect if the value of the checkboxes within the JTables changes, but for some reason it only works for my first table.

Here is my code:

/*
 * 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 javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

/**
 *
 * @author Lenovo
 */
public class TaskFrame extends javax.swing.JFrame {
    
    /**
     * Creates new form Main
     */
    public TaskFrame() {
        initComponents();
        this.setLocationRelativeTo(null);
        taskList t = new taskList();
       
        TableModel modelA = jtblTodayTasks.getModel();
         modelA.addTableModelListener(new TableModelListener(){
            @Override
        public void tableChanged(TableModelEvent e) {
            int row = e.getFirstRow();
            int column = e.getColumn();
            if (column == 4) {
                int input = JOptionPane.showConfirmDialog(null, "Set task as completed?", "Confirm Completion", JOptionPane.YES_NO_OPTION);;
                if(input == 0){
                taskList a = new taskList();
                int ID = Integer.parseInt(modelA.getValueAt(row, 0).toString());
                boolean completed;
                Boolean checked = (Boolean) modelA.getValueAt(row, column);
                if (checked) {
                    completed = true;
                } else {
                    completed = false;
                }
                a.updateCompleted(ID, completed);
                
                }else{
                    TaskFrame.this.dispose();
                    new TaskFrame().setVisible(true);
                }
            }
        }
        });
        TableModel modelB = jtblTomTasks.getModel();
         modelB.addTableModelListener(new TableModelListener(){
            @Override
        public void tableChanged(TableModelEvent e) {
            int row = e.getFirstRow();
            int column = e.getColumn();
            if (column == 4) {
                int input = JOptionPane.showConfirmDialog(null, "Set task as completed?", "Confirm Completion", JOptionPane.YES_NO_OPTION);;
                if(input == 0){
                taskList a = new taskList();
                int ID = Integer.parseInt(modelB.getValueAt(row, 0).toString());
                boolean completed;
                Boolean checked = (Boolean) modelB.getValueAt(row, column);
                if (checked) {
                    completed = true;
                } else {
                    completed = false;
                }
                a.updateCompleted(ID, completed);
                
                }else{
                    TaskFrame.this.dispose();
                    new TaskFrame().setVisible(true);
                }
            }
        }
        });
        
        jtblTodayTasks.setModel(t.filljtblTodayTasks(jtblTodayTasks));
        jtblTomTasks.setModel(t.filljtblTomTasks(jtblTomTasks));
        
        jtblTodayTasks.setAutoCreateRowSorter(true);
        jtblTomTasks.setAutoCreateRowSorter(true);
    }

    
    /**
     * 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() {

        tabbedPane = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtblTodayTasks = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtblTomTasks = 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);

        tabbedPane.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
        tabbedPane.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            tabbedPaneMouseClicked(evt);
        }
        });

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

        tabbedPane.addTab("Due Today", jScrollPane1);

        jtblTomTasks.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
        jtblTomTasks.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, false
            };

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

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

        tabbedPane.addTab("Tomorrow", jScrollPane3);

        getContentPane().add(tabbedPane);
        tabbedPane.setBounds(230, 80, 530, 450);               

    /**
     * @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.JScrollPane jScrollPane2;
    private javax.swing.JTable jtblTodayTasks;
    private javax.swing.JTable jtblTomTasks;
    private javax.swing.JTabbedPane tabbedPane;
    // End of variables declaration                   
}

taskList class populates the tables with data from an access database. Please help me get the checkbox listener to work for both tables. Thank you!




Aucun commentaire:

Enregistrer un commentaire