开发者

multiple instance of a JButton listener event in JLists

开发者 https://www.devze.com 2023-01-24 14:46 出处:网络
I have created a dialog with two JLists displayed and a button that ta开发者_开发技巧kes the selected value from the second JList and does something (say it outputs the selected value). The list of va

I have created a dialog with two JLists displayed and a button that ta开发者_开发技巧kes the selected value from the second JList and does something (say it outputs the selected value). The list of values from the second JList is updated according to the selection of the value from the first JList.

When the dialog is displayed initially, the button is disabled. When a value is selected from the first and then from the second JList, the button is enabled an the required selection listener is added to it.

The problem is that every time the button is clicked the number of output messages is equal to the time a value of the second JList is selected. For example if I select a value from the second JList, then I change my mind and select another value, the click of the button will output the message two times. Does anyone know a method to prevent such a thing?


Your ListSelectionListener should check for (e.getValueIsAdjusting() == false) otherwise you'll respond to all of user's selections and not just the final one.


Yes: don't cache the selections, just process the actual selection in your second list.

If possible, post the code that is executed once your button is pressed. I guess, you have some sort of collection (a list or queue) that stores all the selections you do on the dialog and when you press the button, each stored selection is processed.

This looks like an intended behaviour, because you usually don't code this by accident ;)

If it is intended and you just want to eliminate duplicates, consider using a Set instead of a list, as a Set will only contain unique values.


It does perfectly what it should do.

It fires two events,

1> Selection is removed from first item.

2> Selection is done to second item.

So as fbcocq said, you should check for getValueIsAdjusting(). Check this out, it'll help.


Are you adding an ActionListener to the button every time you enable it?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号