如何在java中创建自定义监听器?
我想知道如何在java中设置我们自己的监听器。例如,我有一个将数字从1增加到100的函数。我想在值达到50时设置一个监听器。我该怎么做?请建议我任何教程。
I want to know about how to set our own Listeners in java.For example I have a function that increments number from 1 to 100. i want to set a listener when the value reaches 50. How can i do that? Pls suggest me any tutorial.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
https://stackoverflow.com/a/6270150/3675925
您可能想查看观察者模式。
可以帮助您入门的示例代码:
以下是一些
https://stackoverflow.com/a/6270150/3675925
You probably want to look into the observer pattern.
Here's some sample code to get you started:
查看使用侦听器的任何类的源代码。事实上,这很简单:
MyListener
MyListener
列表至于观察者模式以及一些Java代码,请查看wikipedia。
Have a look at the source of any class that uses listeners. In fact it's quite easy:
MyListener
MyListener
As for the observer pattern along with some Java code have a look at wikipedia.
没有内置机制允许您将侦听器附加到所有变量。您想要观看的对象需要为其提供支持。例如,它可以成为 Observable 并向其观察者触发 onChange 事件(您还必须确保其被跟踪)。
There is no built-in mechanism that would allow you to attach listeners to all variables. The object you want to watch needs to provide the support for that by itself. For example it could become Observable and fire off onChange events to its Observers (which you also have to ensure are being tracked).
我建议您针对您的用例使用 EventBus 。它有一个很好的API设计并且易于使用。请查看他们的入门部分,了解其工作原理。
I would recommend using EventBus for your use case. It has a nice API design and is easy to use. Have a look at their Getting Started section to see how it works.
您可以使用 Signals 库。它看起来像这样:
免责声明:我是 Signals 的作者。
You can use the Signals library for it. It will look like that:
Disclaimer: I am the author of Signals.