Java中的回调与接口

回调是一种模式,可以指出某个特定事件下发生采取的特定动作。

比如点下鼠标会采取什么行动,下面先采取一些比较简单的方法。

package timer;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

public class TimerTest {

    public static void main(String[] args){
        ActionListener listener=new TimePrinter();

        //construct a timer that calls the listener
        Timer t=new Timer(10000,listener);
        t.start();
        JOptionPane.showMessageDialog(null,"quit program?");
        System.exit(0);
    }
}

class TimePrinter implements ActionListener{

    public void actionPerformed(ActionEvent event){
        System.out.println("At the tone,the time is "+new Date());
        Toolkit.getDefaultToolkit().beep();
    }
}
 
 

会实现每十秒钟出现一个弹框。

猜你喜欢

转载自blog.csdn.net/Billy1900/article/details/80636660