单击JTable行时,valueChanged(ListSelectionEvent e)方法多次调用

时间:2016-07-27 04:32:59

标签: jframe jtable

我有多列的JTable。当我单击表行时,值多次更改方法调用,最后抛出错误

  

java.lang.ArrayIndexOutOfBoundsException:-1

我的代码是

subjectTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            System.out.println("Value IS Adjusting --> " + e.getValueIsAdjusting());

             try {

                if(subjectTable.getSelectedRow() == -1)
                    return;

                if(!e.getValueIsAdjusting()) {

                    System.out.println("Selected Row --> " + subjectTable.getSelectedRow());
                    System.out.println("Selected Value of Column 0 --> " + subjectTable.getValueAt(subjectTable.getSelectedRow(), 0).toString());

                    cmbClass.setSelectedItem(subjectTable.getValueAt(subjectTable.getSelectedRow(), 0).toString());
                    txtSubjectName.setText(subjectTable.getValueAt(subjectTable.getSelectedRow(), 1).toString());
                    txtFullMarks.setText(subjectTable.getValueAt(subjectTable.getSelectedRow(), 2).toString());
                    txtPassMarks.setText(subjectTable.getValueAt(subjectTable.getSelectedRow(), 3).toString());
                    cmbGrade.setSelectedItem(subjectTable.getValueAt(subjectTable.getSelectedRow(), 4).toString());
                }
            } catch (IndexOutOfBoundsException ex) {
                ex.printStackTrace();
                new KILogger("Error in the value changed, Edit Subject table", ex);
            }
        }
    });

我得到了这样的错误:

enter image description here

1 个答案:

答案 0 :(得分:1)

我不知道这是什么问题。但现在通过以下代码解决了这个问题:

subjectTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {

             try {

                if(subjectTable.getSelectedRow() == -1)
                    return;

                if(!e.getValueIsAdjusting()) {

                    txtSubjectName.setText(subjectTable.getValueAt(subjectTable.getSelectedRow(), 1).toString());
                    txtFullMarks.setText(subjectTable.getValueAt(subjectTable.getSelectedRow(), 2).toString());
                    txtPassMarks.setText(subjectTable.getValueAt(subjectTable.getSelectedRow(), 3).toString());
                    cmbGrade.setSelectedItem(subjectTable.getValueAt(subjectTable.getSelectedRow(), 4).toString());
                }
            } catch (IndexOutOfBoundsException ex) {
                ex.printStackTrace();
                new KILogger("Error in the value changed, Edit Subject table", ex);
            }
        }
    }); `