Search code examples
javaswingjtablelistselectionlistener

NullPointerException in Clicking a row in JTable


I want to activate a button if I click an empty 8th column in my Jtable. But I'm getting this:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at records$1.valueChanged(records.java:57)

Here's my code:

tb_records.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent event) {

                int row = tb_records.getSelectedRow();
                DefaultTableModel model = (DefaultTableModel)tb_records.getModel();
                String hehe = (String) model.getValueAt(row, 7);

                if(!hehe.equals("")) {
                    b_extend.setEnabled(false);
                }
                else {
                    b_extend.setEnabled(true);
                }
            }
        });

Solution

  • I made few changes to your code, may be help.

    .(new ListSelectionListener(){
                public void valueChanged(ListSelectionEvent e) {
    
                if (! e.getValueIsAdjusting() ) {
                  ListSelectionModel d = (ListSelectionModel)e.getSource();
                  if(d.getLeadSelectionIndex() != -1){
                       String hehe = (String) model.getValueAt(d.getLeadSelectionIndex(), 7);
                       b_extend.setEnabled("".equals(hehe));
                  }
                }
    
                }
            });