Java by API/javax.swing/Timer

Материал из Java эксперт
Перейти к: навигация, поиск

new Timer(int value, ActionListener act)

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class MainClass {
  public static void main(String args[]) {
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        System.out.println("Hello World Timer");
      }
    };
    Timer timer = new Timer(500, actionListener);
    timer.start();
  }
}





Timer: start()

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class MainClass {
  public static void main(String args[]) {
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        System.out.println("Hello World Timer");
      }
    };
    Timer timer = new Timer(500, actionListener);
    timer.start();
  }
}





Timer: stop()

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
class MainClass extends JFrame {
  Timer timer;
  int counter;
  MainClass(String title) {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ActionListener a = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Counter = " + counter);
        if (++counter > 10) {
          timer.stop();
          System.exit(0);
        }
      }
    };
    timer = new Timer(300, a);
    timer.start();
    pack();
    setVisible(true);
  }
  public static void main(String[] args) {
    new MainClass("Timer Demo1");
  }
}