Java Swing Timer class

Description

Java Swing Timer class

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Main extends JPanel {

   public Main() {
      final JButton animButton = new JButton("<html><font size=+2>Press Me!</font>");
      animButton.addMouseListener(new MouseAdapter() {

         Color startColor = Color.BLACK;
         Color endColor = Color.RED;
         Color currentColor = startColor;
         int animDuration = 250;
         long startTime;
         Timer timer = new Timer(30, new ActionListener() {

            @Override//  ww w .ja v a 2  s  .  com
            public void actionPerformed(ActionEvent e) {
               long currentTime = System.nanoTime() / 1000000;
               long totalTime = currentTime - startTime;
               if (totalTime > animDuration) {
                  startTime = currentTime;
                  timer.stop();
                  return;
               }

               // interpolate
               float fraction = (float) totalTime / animDuration;
               int red = (int) ((1 - fraction) * startColor.getRed() + fraction * endColor.getRed());
               int green = (int) ((1 - fraction) * startColor.getGreen() + fraction * endColor.getGreen());
               int blue = (int) ((1 - fraction) * startColor.getBlue() + fraction * endColor.getBlue());
               currentColor = new Color(red, green, blue);
               animButton.setForeground(currentColor);

               repaint();
            }
         });

         @Override
         public void mouseEntered(MouseEvent e) {
            currentColor = startColor;
            startTime = System.nanoTime() / 1000000;
            timer.start();
         }

         @Override
         public void mouseExited(MouseEvent e) {
            currentColor = startColor;
            animButton.setForeground(currentColor);
            repaint();
            timer.stop();
         }
      });

      add(animButton);
   }

   public static void main(String[] args) {
      // create frame for Main
      JFrame frame = new JFrame("java2s.com");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      Main Main = new Main();
      frame.add(Main);
      frame.setSize(300, 210);
      frame.setVisible(true);
   }
}



PreviousNext

Related