JList fires valueChanged twice when a value is changed via mouse
Asked Answered
B

2

26

I recently encountered a bug in java where JList will fire the valueChanged() method twice when changing a value with the mouse, and only once when changing a value with the keyboard. I just found a bug regarding this on Oracle's website (apparently, the bug is more than twelve years old), and I'm wondering if anyone can explain to me why Oracle has decided that this isn't a defect (not to mention that getValueIsAdjusting() returns false when the keyboard is used).

For anyone having this issue, I found that simply checking for when getValueIsAdjusting() is false, then running the rest of my method will get around the issue.

Brachy answered 17/9, 2012 at 14:38 Comment(2)
Also see https://mcmap.net/q/535530/-java-listselectionlistener-interface-with-keyboardTorin
it's not a bug, it's a feature ;-) Seriously, it is well known (cough .. forget about it myself occasionally) that most of the time only notifications with !getIsValueAdjusting are relevant for application code. Besides that, what exactly are you complaining about?Rabato
B
50

There is a simple explanation.
When you are applying selection with mouse you perform a list of actions:

1. Press left mouse button on some element
- list selects an element under the mouse and fires 1st event
- also here you will get getValueIsAdjusting=true since the mouse is not yet released

2. You might drag mouse without releasing it to change selection
- list will fire an additional event for each selection change made
- getValueIsAdjusting will be also true for each of those events since you are still making changes

3. You release mouse
- list will fire the final event - selection operation is finished
- getValueIsAdjusting=false now, you can do whatever you want with final selection

To summ up - those additional events are fired to let you completely control list behavior on selection changes (on selection change sequence to be exact). You might want to ignore the selection changes when getValueIsAdjusting=true since there always will be a final event with getValueIsAdjusting=false which will inform you that selection changes are finished.

Also, when you change selection with key buttons list wouldn't know if you are going to change it after first key press or not, so getValueIsAdjusting will be always false for such changes.

Ballet answered 17/9, 2012 at 14:53 Comment(0)
P
33

There is a simple solution:

private void jList1 ValueChanged(javax.swing.event.ListSelectionEvent evt) { 

    if (!evt.getValueIsAdjusting()) {//This line prevents double events

    }

}                                     
Patroclus answered 22/8, 2014 at 13:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.