简体   繁体   中英

Retrieving status of JCheckbox inside a JTable

For some reason, i cannot find out what is wrong with my code. Basically

  1. I have a counter (total) initialized to 2 in this case
  2. Increment to a max of 6, each time a JCheckbox is checked (in this case 4 )and throws a message when too much is clicked.
  3. At first, it throws null pointer when exactly a total of 6 is checked; but works fine if more than 6 checkboxes are selected, then reduced to 6 with more than one button click.

Can anyone guide me to where it is messing with my head? Thank you very much.

public void panelThree(JTable user, JButton save, JButton logout, JButton exit, int j) {
    System.out.println("J in external main is: " + j);
    save.addActionListener(new ActionListener() {
        boolean arr[] = new boolean[user.getRowCount()];

        public void actionPerformed(ActionEvent e) {
            int total = j;
            System.out.println("Total in listener is: "+total);
            System.out.println("No of rows: " + user.getRowCount());
            for (int z = 0; z < arr.length; z++) {
                arr[z] = false;
            }
            for (int i = 0; i < user.getRowCount(); i++) {                  
                if (Boolean.valueOf(user.getModel().getValueAt(i, 3).toString()) == true) {
                    if (arr[i] == false) {
                        arr[i] = true;
                        total++;
                    }
                } else {
                    if (arr[i] == true) {
                        arr[i] = false;
                        total--;
                    }
                }
            }
            System.out.println("Total is: " + total);
            if (total > 6) {
                JOptionPane.showMessageDialog(null, "Please choose up to a maximum of " + (6 - j) + " modules");
            } else {
                int reply = JOptionPane.showConfirmDialog(null, "Are you sure to enroll in these modules?", "Yes", JOptionPane.YES_NO_OPTION);
                if (reply == JOptionPane.YES_OPTION) {
                    JOptionPane.showMessageDialog(null, "Enrollment Successful");
                }
            }
        }
    });
}

The line if (Boolean.valueOf(user.getModel().getValueAt(i, 3).toString()) == true) seems to be responsible for all the error all the edit i am making console says null pointer at that line

Your table seems to contain null values. So you need to consider it in your check. Something like this:

if (user.getModel().getValueAt(i, 3) == Boolean.TRUE)

If my suggestion don't work please provide a SSCCE so we can also reproduce your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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