开发者

Java: JList ListSelectionListener only on MouseClick

开发者 https://www.devze.com 2023-02-18 00:02 出处:网络
I\'m fairly new to Java, and have exhausted my Google\'ing for this problem with selection on a JList component.I have a list of strings that dynamically cha开发者_如何学JAVAnge when the user clicks v

I'm fairly new to Java, and have exhausted my Google'ing for this problem with selection on a JList component. I have a list of strings that dynamically cha开发者_如何学JAVAnge when the user clicks various JButtons. My JList selection mode is set to SINGLE_SELECTION, and the ListSelectionModel is registered to a custom ListSelectionChangeHandler that implements ListSelectionListener.

My problem is that every time the JList model's contents get modified (by clicking a JButton), the ListSelectionChangeHandler gets called and a NullPointerException occurs - e.g. The user has an item selected in the list, clicks a button, the list contents change, and the listener gets called. I want the ListSelectionListener to only perform some action when a MouseClick fires the event. How can I prevent my listener from firing when the model data gets modified?

Relevant Code:


this.suggestionsList = new JList();
this.suggestionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

ListSelectionModel model = this.suggestionsList.getSelectionModel(); model.addListSelectionListener(new ListSelectionChangeHandler());

class ListSelectionChangeHandler implements ListSelectionListener {

@Override public void valueChanged(ListSelectionEvent arg0) { Object selectedValue = suggestionsList.getSelectedValue(); // Perform action on selectedValue // Enable/Disable components as needed }

}

Thanks for the help!


The easiest way, of which I can think, is to make a switcher - boolean variable, that will be checked every time in your listener before it starts to really do something. Then you can start all of you modifications with switching this variable off. In case of multithreading, you may need some synchronization here.

0

精彩评论

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

关注公众号