选择行时ArrayIndexOutOfBoundsException(-1)

时间:2015-12-16 19:49:51

标签: java swing jtable

我试图获取有人在JTable中双击的行号。触发器触发,但它并不认为我已经点击了一行。当我检索行号时,它总是-1:

informationTable.addMouseListener(new java.awt.event.MouseAdapter() {
    @Override
    public void mouseClicked(java.awt.event.MouseEvent evt) {
        if (evt.getClickCount() == 2) {
            int row = informationTable.getSelectedRow();
            System.out.println(row); // always -1
            informationTable.setValueAt('1', row, MEAL_COL); // fails...
        }
    }
});

为什么这不能给我正确的行,任何一行呢?

编辑:

为了回答我如何关闭编辑(对于特定列),我重写了DefaultTableModel类的isCellEditable方法,如下所示:

private class KAMDTM extends DefaultTableModel {
    private final boolean[] canEdit = new boolean[] {false, false, false, false, false, false, true};

    public KAMDTM(Object[][] data, String[] cols) {
        super(data, cols);
    }
    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit[columnIndex];
    }
}

1 个答案:

答案 0 :(得分:2)

你可以从这篇文章得到答案:Double click listener on JTable in Java,看看代码建议使用的第二个答案:

Point p = evt.getPoint();
int row = table.rowAtPoint(p);