简体   繁体   English

java Swing Listeners:彼此聆听的组件

[英]java Swing Listeners: components listening at each others

I want to code two JList (categories and items). 我想编写两个JList(类别和项目)。 When I click one category it should select all the items for that category and when I click on one item it should select its categories. 当我点击一个类别时,它应该选择该类别的所有项目,当我点击一个项目时,它应该选择其类别。 So both JList will have a ListSelectionListener listening at each other and changing the selection. 因此,两个JList都会有一个ListSelectionListener相互监听并更改选择。

Should I fear about some a kind of " loop " ? 我应该担心某种“ 循环 ”吗? Is there a way to tell that an Event has been consumed ? 有没有办法告诉事件已被消耗? how do people manage that kind of situation ? 人们如何处理这种情况?

Thanks 谢谢

As you have imagined, each time make selection on listA , you will trigger a ListSelectionEvent to be fired on your listener for listA , whose job it is to find all appropriate items in listB to select. 如你想象,在每次进行选择listA ,你会触发ListSelectionEvent在您的侦听器被解雇listA ,它的任务是找到所有适当项目listB选择。 Forcing selection then on listB will trigger events to be handled by your listB listener. 强制选择然后在listB上将触发listB侦听器处理的事件。 This will in turn force selection on listA . 这将反过来强制listA选择。 Simply using two listeners doesnt solve the problem. 简单地使用两个听众并不能解决问题。

I see two options: 我看到两个选择:

1 - use a single listener. 1 - 使用单个监听器。 This listener will need to test the source of the event by using the getSource method on the ListSelectionEvent . 此侦听器需要使用ListSelectionEvent上的getSource方法来测试事件的来源。 If the source is listB , remove your listener from the listenerlist of listA , force selection on listA and then readd. 如果源是listB ,从该listenerlist删除您的听众listA ,强迫的选择listA ,然后READD。

list1.removeListSelectionListener(this);
list1.setSelectedIndex(e.getFirstIndex()); //this would have to be played with to allow for intervals
list1.addListSelectionListener(this);`

2 - use two listeners, however, to avoid the loop, you would need to test whether the item is already selected before attempting to select it. 2 - 但是,使用两个侦听器来避免循环,您需要在尝试选择项之前测试该项是否已被选中。 If it is already selected, dont reselect it. 如果已经选中,请不要重新选择它。

Look at the Beans Binding API . 看看Beans Binding API Here's a tutorial for NetBeans. 这是NetBeans的教程

Two Listeners is good way how to do that, don't worry. 两个听众是如何做到这一点的好方法,不用担心。 Just be sure you create listeners only ONCE, not in loop. 确保只创建侦听器ONCE,而不是循环。

Check where your focus is. 检查您的焦点在哪里。 If your listener listens to component A and the focus is not on A, do not update other components as A is not the component changed by the user. 如果侦听器侦听组件A并且焦点不在A上,则不要更新其他组件,因为A不是用户更改的组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM