Java Tutorial/Swing/Swing Timer

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

14. A rotating and scaling rectangle.

   <source lang="java">

import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class SwingTimerBasedAnimationScaleRotate extends JPanel implements ActionListener {

 Timer timer;
 private double angle = 0;
 private double scale = 1;
 private double delta = 0.01;
 Rectangle.Float r = new Rectangle.Float(20, 20, 200, 200);
 public SwingTimerBasedAnimationScaleRotate() {
   timer = new Timer(10, this);
   timer.start();
 }
 public void paint(Graphics g) {
   int h = getHeight();
   int w = getWidth();
   Graphics2D g2d = (Graphics2D) g;
   g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
   g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
   g2d.translate(w / 2, h / 2);
   g2d.rotate(angle);
   g2d.scale(scale, scale);
   g2d.fill(r);
 }
 public static void main(String[] args) {
   JFrame frame = new JFrame("Moving star");
   frame.add(new SwingTimerBasedAnimationScaleRotate());
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setSize(420, 250);
   frame.setLocationRelativeTo(null);
   frame.setVisible(true);
 }
 public void actionPerformed(ActionEvent e) {
   if (scale < 0.01) {
     delta = -delta;
   } else if (scale > 0.99) {
     delta = -delta;
   }
   scale += delta;
   angle += 0.01;
   repaint();
 }

}</source>





14. Fade out an image: image gradually get more transparent until it is completely invisible.

   <source lang="java">

import java.awt.AlphaComposite; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class FadeOutImage extends JPanel implements ActionListener {

 Image myImage = new ImageIcon("a.jpg").getImage();
 Timer timer = new Timer(20, this);
 private float alpha = 1f;
 public FadeOutImage() {
   timer.start();
 }
 public void paint(Graphics g) {
   super.paint(g);
   Graphics2D g2d = (Graphics2D) g;
   g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
   g2d.drawImage(myImage, 10, 10, null);
 }
 public void actionPerformed(ActionEvent e) {
   alpha += -0.01f;
   if (alpha <= 0) {
     alpha = 0;
     timer.stop();
   }
   repaint();
 }
 public static void main(String[] args) {
   JFrame frame = new JFrame("Fade out");
   frame.add(new FadeOutImage());
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setSize(300, 250);
   frame.setVisible(true);
 }

}</source>





14. Font size animation

   <source lang="java">

import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class FontSizeAnimation extends JPanel implements ActionListener {

 Timer timer;
 int x = 1;
 float alpha = 1;
 public FontSizeAnimation() {
   timer = new Timer(8, this);
   timer.setInitialDelay(190);
   timer.start();
 }
 public void paint(Graphics g) {
   super.paintComponent(g);
   Graphics2D g2d = (Graphics2D) g;
   Font font = new Font("Dialog", Font.PLAIN, x);
   g2d.setFont(font);
   FontMetrics fm = g2d.getFontMetrics();
   String s = "Java";
   
   int w = (int) getSize().getWidth();
   int h = (int) getSize().getHeight();
   int stringWidth = fm.stringWidth(s);
   g2d.drawString(s, (w - stringWidth) / 2, h / 2);
 }
 public static void main(String[] args) {
   JFrame frame = new JFrame("FontSizeAnimation");
   frame.add(new FontSizeAnimation());
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setSize(400, 300);
   frame.setLocationRelativeTo(null);
   frame.setVisible(true);
 }
 public void actionPerformed(ActionEvent e) {
   x += 1;
   alpha -= 0.0001;
   repaint();
 }

}</source>





14. Swing Timer action

   <source lang="java">

import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.Timer; public class TimerChangeButtonBackground extends JFrame {

 boolean flag = false;
 JButton button = new JButton("Click to stop");
 Timer timer;
 public TimerChangeButtonBackground() {
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   getContentPane().add(button, "Center");
   button.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       timer.stop();
       button.setBackground(Color.red);
     }
   });
   timer = new Timer(1000, new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       button.setBackground(flag ? Color.green : Color.yellow);
       flag = !flag;
       repaint();
     }
   });
   timer.start();
   pack();
   setVisible(true);
 }
 public static void main(String arg[]) {
   new TimerChangeButtonBackground();
 }

}</source>





14. Swing Timers

  1. javax.swing.Timer can only be used in Swing applications.
  2. javax.swing.Timer is a more appropriate choice over java.util.Timer for Swing applications.
  3. javax.swing.Timer handles thread sharing.
  4. You implement the java.awt.event.ActionListener interface and write your task code in its actionPerformed method.
  5. Ro cancel a task, you use the javax.swing.Timer class"s stop method.



   <source lang="java">

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; public class MainClass {

 public static void main(String[] args) {
   Timer timer = new Timer(1000, new MyTimerActionListener());
   timer.start();
   try {
     Thread.sleep(10000);
   } catch (InterruptedException e) {
   }
   timer.stop();
 }

} class MyTimerActionListener implements ActionListener {

 public void actionPerformed(ActionEvent e) {
   System.out.println("asdf");
 }

}</source>





14. Timer based animation

   <source lang="java">

import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Ellipse2D; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class TimerBasedAnimation extends JPanel implements ActionListener {

 private Ellipse2D.Float ellipse = new Ellipse2D.Float();
 private double esize;
 private double maxSize = 0;
 private boolean initialize = true;
 Timer timer;
 ActionListener updateProBar;
 public TimerBasedAnimation() {
   setXY(20 * Math.random(), 200, 200);
   timer = new Timer(20, this);
   timer.setInitialDelay(190);
   timer.start();
 }
 public void setXY(double size, int w, int h) {
   esize = size;
   ellipse.setFrame(10, 10, size, size);
 }
 public void reset(int w, int h) {
   maxSize = w / 10;
   setXY(maxSize * Math.random(), w, h);
 }
 public void step(int w, int h) {
   esize++;
   if (esize > maxSize) {
     setXY(1, w, h);
   } else {
     ellipse.setFrame(ellipse.getX(), ellipse.getY(), esize, esize);
   }
 }
 public void render(int w, int h, Graphics2D g2) {
   g2.setColor(Color.BLUE);
   g2.draw(ellipse);
 }
 public void paint(Graphics g) {
   super.paintComponent(g);
   Graphics2D g2 = (Graphics2D) g;
   RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
       RenderingHints.VALUE_ANTIALIAS_ON);
   rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
   g2.setRenderingHints(rh);
   Dimension size = getSize();
   if (initialize) {
     reset(size.width, size.height);
     initialize = false;
   }
   this.step(size.width, size.height);
   render(size.width, size.height, g2);
 }
 public void actionPerformed(ActionEvent e) {
   repaint();
 }
 public static void main(String[] args) {
   JFrame frame = new JFrame("TimerBasedAnimation");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.add(new TimerBasedAnimation());
   frame.setSize(350, 250);
   frame.setLocationRelativeTo(null);
   frame.setVisible(true);
 }

}</source>





14. Timer Class

   <source lang="java">

import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; public class TimerSample {

 public static void main(String args[]) {
   Runnable runner = new Runnable() {
     public void run() {
       ActionListener actionListener = new ActionListener() {
         public void actionPerformed(ActionEvent actionEvent) {
           System.out.println("Hello World Timer");
         }
       };
       Timer timer = new Timer(500, actionListener);
       timer.start();
     }
   };
   EventQueue.invokeLater(runner);
 }

}</source>





14. Timer Properties: coalesce

The coalesce property allows for a busy system to throw notifications that haven"t happened yet when a new event needs to be fired.

This means if a timer runs every 500 milliseconds, but its system is bogged down and doesn"t respond for a whole 2 seconds, the timer needs to send only one message, rather than also sending the missing ones. If the setting were false, four messages would still need to be sent.

By default, the coalesce value is true.


14. To turn on log messages

   <source lang="java">

import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; public class TimerSample {

 public static void main(String args[]) {
   Runnable runner = new Runnable() {
     public void run() {
       Timer.setLogTimers(true);
       ActionListener actionListener = new ActionListener() {
         public void actionPerformed(ActionEvent actionEvent) {
           System.out.println("Hello World Timer");
         }
       };
       Timer timer = new Timer(500, actionListener);
       timer.start();
     }
   };
   EventQueue.invokeLater(runner);
 }

}</source>