java 回调

简介

java 回调会传入类作为参数,在类中实现动作接口即可

code

package cn;

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

import javax.swing.JOptionPane;
import javax.swing.Timer;

public class TimerTest {
	public static void main(String[] args) {
		ActionListener listener = new TimePrinter();
		
		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();
	}
}

Result

会有一个选择确认的界面然后如果点击了确认之后程序退出,如果没有点击确认那么会10s中调用listener对象中的actionPerformed来执行相应的动作

Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/13447254.html