As you know, without using !getValueIsAdjusting
when you select a row in a jtable (by clicking) the selection change event fire twice. It doesn't happen if you select a row using the keyboard arrow. To resolve it, you check if getValueIsAdjusting
returns false.
My question is why does the event fire twice if I select a row by clicking it, but not when using the keyboard arrow? And what does getValueIsAdjusting do to resolve it?
As the javadoc which JB Nizet linked to states, getValueIsAdjusting()
checks whether a specific event (a change) is part of a chain, if so it will return true
. It will only return false
when the specified event is the final one in the chain.
In your case, selecting a row by clicking actually fires two events: a mouseDown
and mouseUp
event and both are sent to your event listener. If you correctly implement getValueIsAdjusting()
to return whenever the value is true
, you will only act on the final event in the chain, which is the mouseUp
event that fires when you let go of the left mouse button.
The Java Tutorials include an example that captures events, you can use that to log the selection events and experiment with it yourself. Remove the return on the event.getValueIsAdjusting()
check to log every event that's fired.
String interessen[]= {"aaaaaaa", "bbbbbbbb", "ccccccccc", "ddddddd"};
myList = new JList<>(interessen);
myList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if(!e.getValueIsAdjusting())
System.out.println(myList.getSelectedValue());
}
});
The code above shows what getValueIsAdjusting do, without these method an event may be called eg. two times (it depends of event).
Output without getValueIsAdjusting loop after clicking on some element of JList: aaaaaaa aaaaaaa
with loop: aaaaaaa
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With