当对象状态改变时在Java中触发事件 [英] Triggering events in Java when an object's state changes

查看:412
本文介绍了当对象状态改变时在Java中触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java对象,其状态会随着时间的推移而变化.当对象中的某个字段达到某个值时,我希望触发外部事件.

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.

我知道Swing通过侦听器处理这种模式-我正在为该项目使用Swing-但我不确定哪种侦听器将应用于这种情况.用户不会更改对象的状态,并且侦听器似乎仅由用户的操作触发.

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组件-它在主线程的后台运行.

Edit: The object that I'm monitoring isn't itself a Swing component - it runs in the background in the main thread.

推荐答案

您可能想看看

You might want to have a look at java.util.Observable, which is designed just for this purpose.

这是有关Observer和Observable的JavaWorld教程:

Here's a JavaWorld tutorial on Observer and Observable:

这篇关于当对象状态改变时在Java中触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆