当对象的状态改变时触发 Java 中的事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4130673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Triggering events in Java when an object's state changes
提问by chimeracoder
I have an object in Java whose state changes over the course of time. When one of the fields in the object reaches a certain value, I want an external event to be triggered.
我有一个 Java 对象,它的状态随着时间的推移而变化。当对象中的一个字段达到某个值时,我希望触发一个外部事件。
I know Swing handles this pattern through Listeners - and I am using Swing for this project - but I'm not sure what kind of Listener would apply to this case. The object's state is not being changed by the user, and Listeners seem to be triggered only by users' actions.
我知道 Swing 通过 Listeners 处理这种模式 - 我在这个项目中使用 Swing - 但我不确定什么样的 Listener 将适用于这种情况。对象的状态不会被用户改变,监听器似乎只能由用户的操作触发。
Edit: The object that I'm monitoring isn't itself a Swing component - it runs in the background in the main thread.
编辑:我正在监视的对象本身不是 Swing 组件 - 它在主线程的后台运行。
回答by Grodriguez
You might want to have a look at java.util.Observable, which is designed just for this purpose.
您可能想查看专为此目的而设计的java.util.Observable。
Here's a JavaWorld tutorial on Observer and Observable:
这是关于 Observer 和 Observable 的 JavaWorld 教程:
回答by Vijay Mathew
Whether that state is changed by the user or not really do not matter. You can invoke the listener callbacks from the method that changes the state and make sure that the state of the object could be changed only through that method:
该状态是否被用户改变并不重要。您可以从更改状态的方法调用侦听器回调,并确保只能通过该方法更改对象的状态:
class A {
public void changeState(State newState) {
state = newState;
for (SomeEventListenerInterface el : listeners) {
el.nofity(this, newState);
}
}
}
回答by camickr
and Listeners seem to be triggered only by users' actions.
和 Listeners 似乎只能由用户的操作触发。
Not always. For example when you change the property of many Swing components (background, font, etc) a PropertyChangeEvent is fired.
不总是。例如,当您更改许多 Swing 组件(背景、字体等)的属性时,会触发 PropertyChangeEvent。
I would suggest you can also use this event. Read the section from the Swing tutorial on How to Write a Property Change Listenerfor an example.
我建议您也可以使用此事件。阅读 Swing 教程中关于如何编写属性更改侦听器的部分以获取示例。