NullPointerException in Clicking a row in JTable

576 views Asked by At

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

There are 2 answers

0
nachokk On BEST ANSWER

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

            }
        });
0
mKorbel On

(not an answer, I'd be talking about simple way)

  1. change ListSelectionMode to SINGLE_...., then only one row can be selected, otherwise you have to loop inside array of selected rows

  2. test if (row > -1) == no row is selected, if passed then you can to

  3. for better help sooner post an SSCCE, short, runnable, compilable, with hardcoded value for JTable