有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中创建自定义事件

我想用Java做类似的事情,但我不知道怎么做:

当“对象1打招呼”事件发生时, 然后,对象2通过说“你好”来响应该事件

有人能给我一个提示或示例代码吗


共 (1) 个答案

  1. # 1 楼答案

    有三种不同的设置方法:

    1. ThrowerCatcher
    2. CatcherThrower的内部
    3. ThrowerCatcher在本例中的另一个类内Test

    THE WORKING GITHUB EXAMPLE I AM CITING默认为选项3,要尝试其他方法,只需取消对要成为main的类的“Optional”代码块的注释,并将该类设置为build.xml文件中的${Main-Class}变量:

    抛出代码需要4件事:

    import java.util.*;//import of java.util.event
    
    //Declaration of the event's interface type, OR import of the interface,
    //OR declared somewhere else in the package
    interface ThrowListener {
        public void Catch();
    }
    /*_____________________________________________________________*/class Thrower {
    //list of catchers & corresponding function to add/remove them in the list
        List<ThrowListener> listeners = new ArrayList<ThrowListener>();
        public void addThrowListener(ThrowListener toAdd){ listeners.add(toAdd); }
        //Set of functions that Throw Events.
            public void Throw(){ for (ThrowListener hl : listeners) hl.Catch();
                System.out.println("Something thrown");
            }
    ////Optional: 2 things to send events to a class that is a member of the current class
    . . . go to github link to see this code . . .
    }
    

    类文件中需要2件东西才能接收来自类的事件

    /*_______________________________________________________________*/class Catcher
    implements ThrowListener {//implement added to class
    //Set of @Override functions that Catch Events
        @Override public void Catch() {
            System.out.println("I caught something!!");
        }
    ////Optional: 2 things to receive events from a class that is a member of the current class
    . . . go to github link to see this code . . .
    }