[英]Java - Create a Custom event and listener
我试图用Java创建一个自定义事件和监听器。 我已经看过这些文章和问题了:
https://www.javaworld.com/article/2077333/core-java/mr-happy-object-teaches-custom-events.html
但我仍然无法真正地围绕它。 这就是我想要的:
我有一个String
对象,其内容随程序运行而变化。 我希望能够为该字符串添加一个监听器,该监听器包含一个特定的字符串,并且当它运行一段代码时。 我想这样使用它:
String string = "";
//String.addListener() and textListener need to be created
string.addListener(new textListener("hello world") {
@Override
public void onMatch(
System.out.println("Hello world detected");
)
}
//do a bunch of stuff
string = "The text Hello World is used by programmers a lot"; //the string contains "Hello World", so the listener will now print out "Hello world detected"
我知道可能有更简单的方法来做到这一点,但我想知道如何这样做。
谢谢@Marcos Vasconcelos指出你不能向String
对象添加方法,所以有没有办法可以使用@Ben指出的自定义类?
所以我做了一个最小的例子,也许会帮助你:
您需要为您的侦听器提供一个界面:
public interface MyEventListener
{
public void onMyEvent();
}
然后,对于String,您需要一些也处理事件的包装器类
public class EventString
{
private String myString;
private List<MyEventListener> eventListeners;
public EventString(String myString)
{
this.myString = myString;
this.eventListeners = new ArrayList<MyEventListener>();
}
public void addMyEventListener(MyEventListener evtListener)
{
this.eventListeners.add(evtListener);
}
public void setValue(String val)
{
myString = val;
if (val.equals("hello world"))
{
eventListeners.forEach((el) -> el.onMyEvent());
}
}
}
您会看到myString
字段是私有的,只能使用setValue
方法访问。 这是我们可以看到我们的事件条件何时触发。
然后你只需要实现一些,例如:
EventString temp = new EventString("test");
temp.addMyEventListener(() -> {
System.out.println("hello world detected");
});
temp.setValue("hello world");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.