问题描述
我想知道如何为某些东西创建我自己的监听器,并且能够像任何其他监听器一样使用它,例如。
I was wondering how it would be possible to create my own listener for something, and to be able to use it just like any other listener, ex.
public interface Listener {
public void onListen(Event e);
}
然后我的班级
public class test implements Listener {
Object.add(new Listener() {
@Override
public void onListen(Event e) {
}
});
}
我想我真正要问的是我在哪里定义如何检查是否发生了与我创建的监听器有关的事情?
I guess what i'm really asking also is where do I define how to check if something happens pertaining to the listener that I create?
如果其中任何一个没有意义,请告诉我,我会澄清它。
If any of this doesn't make sense, please tell me and I will clarify it.
如果充其量这对你毫无意义,我会试试这个。如何让侦听器检查组合框中的选定选项是否已更改为其他选项。我实际上并不需要一个组合代码监听器,这只是一个例子。
If at best this makes no sense to you, i'll try this. How would I make a listener to check if the selected option in a combobox has changed to a different option. I don't actually need a combobox listener though, that was just an example.
推荐答案
这是一个简短的例子:
private static class Position {
}
private static class Ball {
private ArrayList<FootballObserver> observers = new ArrayList<FootballObserver>();
private Position ballPosition = new Position();
public void registerObserver(FootballObserver observer) {
observers.add(observer);
}
public void notifyListeners() {
for(FootballObserver observer : observers) {
observer.notify(ballPosition);
}
}
public void doSomethingWithFootballPosition() {
//bounce etc
notifyListeners();
}
}
private static interface FootballObserver {
void notify(Position ball);
}
private static class Player implements FootballObserver {
public void notify(Position ball) {
System.out.println("received new ball position");
}
}
public static void main(String... args) {
FootballObserver player1 = new Player();
Ball football = new Ball();
football.registerObserver(player1);
football.doSomethingWithFootballPosition();
}
这篇关于用Java创建自定义监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!