tags:

views:

58

answers:

2

I am developing a JTable with different rows. I would like to associate an event to the selection of a row in this table. I have used the following selection class to provide behaviour to the table selection:

public class TableSelectionListener implements ListSelectionListener{

public Integer item;    

public TableSelectionListener(Integer item){
    this.dialog = item;
}

public void valueChanged(ListSelectionEvent e) {

    System.out.println("The row clicked is "+item);

    }
}

When I create an instance of this table, sai tabletest, I have added the following piece of code:

tabletest.getSelectionModel().addListSelectionListener(new TableSelectionListener(tabletest.getSelectedRow());

The problem is that when I click on one row once, instead of retrieving the related message once, I retrieve the same message several times, suggesting that the actions repeated several times. For example:

The row clicked is 0
The row clicked is 0
The row clicked is 0
The row clicked is 0

Does anyone know where the problem may be?

+3  A: 

Well, that's just normal.

Your selection listener is created with the value of tabletest.getSelectedRow() at its creation table (which is zero). And, as you never change the value of item in your listener, this listener fcan only display 0as a result.

If I were you, I wouold replace the valueChanged() method by something like (although it's untested and I remember strange things happens sometimes when mixing view and model row values) this :

public void valueChanged(ListSelectionEvent e) {
    if(!e.getValueIsAdjusting()) // added as sometimes, multiple events are fired while selection changes
        System.out.println("The row clicked is "+e.getFirstIndex());
}
Riduidel
Well, it doesn't work: if I click the second and third row the message output is correct: "The row clicked is 1" and "The row clicked is 2". However when I click the first row instead of giving me 0 it gives me again 2.
Tony
Alternative approach would be to ask in the listener from the table what rows have been selected.
Carlos
`e.getFirstIndex()` isn't very reliable. use table.getSelectedRow() - it's more stable.
tulskiy
+2  A: 

Firstly, it's perfectly normal to get multiple ListSelectionEvents, while the selection is being changed. You can use the getValueIsAdjusting method to determine when selection has ended (it will return false).

Secondly, there's no need to construct your TableSelectionListener with a row number. When your valueChanged method is called, you can get the index of the first/last selected row (remember it's possibly to select multiple rows in the table, unless you disable that) using e.getFirstIndex() and e.getLastIndex() respectively.

Richard Fearn