Search code examples
javaswingjtablejoptionpanelistselectionlistener

Confirm Dialog showing up multiple times


I have a confirm dialog inside a addListSelectionListener. This fires when I select a row in the table. Then the confirm dialog appears and after I click yes or no it keeps on appearing!

This is my code.

public Reference() {
    initComponents();
    fillTable();
    jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            int prompt = JOptionPane.showConfirmDialog(null, "Are you sure you want to Check Out this item?", "Warning", JOptionPane.YES_NO_OPTION);
            if (prompt == 0) {
                String accessNo = jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString();
                String query = "delete from reference where accessNo=" + accessNo + "";
                if (DB.executeNonQuery(query) > 0) {
                    JOptionPane.showMessageDialog(null, "Check out Successfull!");
                    fillTable();
                } else {
                    JOptionPane.showMessageDialog(null, "Check out Failed!");
                }
            }
        }
    });
}

Solution

  • Ensure that the value is not adjusting in the ListSelectionListener

    public void valueChanged(ListSelectionEvent e) {
       if(!e.getValueAdjusting()) {
          ...
       }
    }   
    

    Ref: How to Write a List Selection Listener