Java Swing How to - Shake JButton animation








Question

We would like to know how to shake JButton animation.

Answer

//  w  w w . j  a  v a2 s. c o  m
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Main implements Runnable {

  private JButton button;

  public static void main(String[] args) throws Exception {
    SwingUtilities.invokeLater(new Main());
  }

  @Override
  public void run() {
    button = new JButton("Shake with this Button  ");
    button.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        shakeButton();
      }
    });
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(button, BorderLayout.SOUTH);
    frame.setSize(240, 160);
    frame.setVisible(true);
  }

  private void shakeButton() {
    final Point point = button.getLocation();
    final int delay = 75;
    Runnable r = new Runnable() {
      @Override
      public void run() {
        for (int i = 0; i < 30; i++) {
          try {

            moveButton(new Point(point.x + 5, point.y));
            Thread.sleep(delay);
            moveButton(point);
            Thread.sleep(delay);
            moveButton(new Point(point.x - 5, point.y));
            Thread.sleep(delay);
            moveButton(point);
            Thread.sleep(delay);
          } catch (InterruptedException ex) {
            ex.printStackTrace();
          }
        }
      }
    };
    Thread t = new Thread(r);
    t.start();
  }

  private void moveButton(final Point p) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        button.setLocation(p);
      }
    });
  }
}