Rabbit Guy
Rabbit Guy

Reputation: 1892

ArrayIndexOutOfBoundsException (-1) when selecting a row

I am attempting to obtain the row number someone has double-clicked in a JTable. The trigger fires, but it doesn't think I've clicked a row. When I retrieve the row number it is always -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...
        }
    }
});

Why is this not giving me the correct row, any row for that matter?

Edit:

To answer how I turned off editing (for specific columns) I overrode the isCellEditable method of the DefaultTableModel class as follows:

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

Upvotes: 1

Views: 127

Answers (1)

SomeDude
SomeDude

Reputation: 14238

You can probably get answer from this post : Double click listener on JTable in Java , look at the second answer the code suggests to use :

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

Upvotes: 2

Related Questions