Alex Huber
Alex Huber

Reputation: 503

JTable, TableColumnModelListener detecting selected row

what i want to accomplish is the following: If the user focuses the 5th column of a row in my JTable (either by clicking on it or pressing tab until he reaches the 5th cell), i show a dialog. The result of the dialog will then be put in that cell. To access that cell i need to know the row and the column that is focused.

The problem that i am facing now is, that if i click on the cell, before focusing anything else in the table, getSelectedRow() returns -1, while getSelectedColumn() returns the right column.

Question: How can i determine the selected row on the first click in the table. Or is my only option to do a big workaround to handle that first click separately.

new TableColumnModelListener() {
    .
    .
    .
    @Override
    public void columnSelectionChanged(ListSelectionEvent e) {
        System.out.println(getSelectedColumn()); // this is correct
        System.out.println(getSelectedRow());  // -1 on first click in JTable
    }    
}

Upvotes: 1

Views: 1869

Answers (2)

kleopatra
kleopatra

Reputation: 51536

The problem arises because row and column selection are handled by two unrelated models: a trigger that changes the selection in both (f.i. a mousePressed) will do so by changing first the one, then the other (with no guarantee on sequence). Consequently, at the time of receiving the change notification on one, you can't know whether or not the other is already changed or not.

To solve, wrap your custom handling of the notification into an invokeLater: this is guaranteed to happen after all pending events are processed:

@Override
public void columnSelectionChanged(ListSelectionEvent e) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            System.out.println(table.getSelectedColumn()); // this is correct
            System.out.println(table.getSelectedRow());  // -1 on first click in JTable
        }
    });
}

Upvotes: 3

Karki64
Karki64

Reputation: 23

try this:

table.addMouseListener(new MouseListener()
    {
        @Override
        public void mousePressed(MouseEvent evt)
        {   
           int row = table.getSelectedRow();
           int col = table.getSelectedColumn();
           System.out.println(row);
           System.out.println(col);
           if (col==4){
               JOptionPane.showInputDialog(null, "hi");
           }
        }

that would give you the selected row and column every time the user clicks. The only disadvantage is that row one would print out 0, therefore you'd have to set (col==4) to trigger the dialog box. this is not a tablecolumnmodellistener though.

Alternatively, you might want to look at this, because, someone seemed to have a similar problem: JTable not returning selected row correctly

Upvotes: 0

Related Questions