javax.swing.Timer的与Lambda的使用

以指定的间隔触发一个或多个ActionEvent s。 示例使用是使用Timer作为绘制其帧的触发器的动画对象。
设置定时器包括创建一个Timer对象,在其上注册一个或多个动作侦听器,并使用start方法启动定时器。 例如,下面的代码创建并启动每秒一次触发一个动作事件(由第一个参数指定定时器Timer构造函数)。 Timer构造函数的第二个参数指定一个侦听器来接收定时器的动作事件。

public class MyTimer {

  public static void main(String[] args){
      int delay = 1000; //milliseconds

        //传统写法
        class actionListenerImpl implements ActionListener{
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("传统方法");
            }
        }
        new Timer(500,new actionListenerImpl()).start();

       //匿名内部类写法
      ActionListener taskPerformer = new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
              System.out.println("时间到了");
          }
      };
      new Timer(delay, taskPerformer).start();


        //Lambda表达式写法
        new Timer(2000,e -> System.out.println("过了两秒钟")).start();

       //javax.swing.Timer 中必须和GUI配合使用
      JOptionPane.showMessageDialog(null, "Quit program?");

  }
}

javax.swing.JOptionPane 1.2

    static void showMessageDialog(Component parent,Object message)
    显示一个包含一条消息和OK按钮的对话框。这个对话框将位于其parent组件的中央。如果parent为null,对话框将显示在屏幕的中央。


javax.swing.Timer 1.2

    Timer(int interval, ActionListener listener)
    构造一个定时器,每隔interval毫秒钟通告listener一次。
    void start()
    启动定时器。一旦启动成功,定时器将调用监听器的actionPerformed。
    void stop()
    停止定时器。一旦停止成功,定时器将不再调用监听器的actionPerformed。

posted @ 2019-10-12 10:17  岸北  阅读(436)  评论(0编辑  收藏  举报