简体   繁体   中英

Creating Custom Listeners In Java

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);

}

And then this in my class

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.

Here is a short 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();
    }

There is no trouble creating the listeners that you need, but you only can apply it to classes that expect it (so you cannot do (new Object()).addMyListener )

You will need to add to the classes where you want to use the listener an addMyListener(MyListener myListener) method. It just stores the listeners that you pass to it in a list for later user. It would be a good idea creating an interface with the addMyListener method (and a fireMyListeners() ) method too.

Of course, you must also provide the code to call the fireMyListeners() method, too. Then the fireMyListeners() will just loop through the listeners and call theirs notification method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM