Re: How to shake a window as MSN or Yahoo Messenger does
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import java.util.Random;
/**
* @author Bart Cremers (bce1716)
* @since Apr 28, 2006
*/
public class ShakeFrame extends JFrame implements Runnable {
private static final int SHAKES = 25;
private static final int SHAKE_FORCE = 5;
private static final Random RND = new Random();
private JButton button;
@Override
protected void frameInit() {
super.frameInit();
JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createEmptyBorder(50, 50, 50,
50));
setContentPane(pane);
button = new JButton("Shake Me !");
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
button.setEnabled(false);
new Thread(ShakeFrame.this).start();
}
});
}
public void run() {
final Rectangle origRect = ShakeFrame.this.getBounds();
for (int i = 0; i < SHAKES; i++) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
int x;
if (RND.nextBoolean()) {
x = SHAKE_FORCE;
} else {
x = -SHAKE_FORCE;
}
int y;
if (RND.nextBoolean()) {
y = SHAKE_FORCE;
} else {
y = -SHAKE_FORCE;
}
ShakeFrame.this.setBounds(origRect.x + x,
origRect.y + y, origRect.width,
origRect.height);
}
});
try {
Thread.sleep(10);
} catch (InterruptedException e) { }
}
ShakeFrame.this.setBounds(origRect); // Reset to original
position
button.setEnabled(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new ShakeFrame();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}