Creating Custom Listeners In Java

前端 未结 2 1202
南笙
南笙 2020-12-30 05:18

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         


        
2条回答
  •  没有蜡笔的小新
    2020-12-30 06:13

    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.

提交回复
热议问题