无意中发现的好玩代码——摇动的java对话框

信息资料来源:http://www.java2s.com/CN/Code/Java/Swing-Components/Shakeadialog.htm

 1 import java.awt.Point;
2 import java.awt.event.ActionEvent;
3 import java.awt.event.ActionListener;
4 import javax.swing.JDialog;
5 import javax.swing.JOptionPane;
6 import javax.swing.Timer;
7
8 public class Main {
9 JDialog dialog;
10 Point naturalLocation;
11 Timer shakeTimer;
12
13 public Main(JDialog d) {
14 dialog = d;
15 }
16
17 public void startShake() {
18 final long startTime;
19
20 naturalLocation = dialog.getLocation();
21 startTime = System.currentTimeMillis();
22 shakeTimer = new Timer(5, new ActionListener() {
23 public void actionPerformed(ActionEvent e) {
24 double TWO_PI = Math.PI * 2.0;
25 double SHAKE_CYCLE = 50;
26
27 long elapsed = System.currentTimeMillis() - startTime;
28 double waveOffset = (elapsed % SHAKE_CYCLE) / SHAKE_CYCLE;
29 double angle = waveOffset * TWO_PI;
30
31 int SHAKE_DISTANCE = 10;
32
33 int shakenX = (int) ((Math.sin(angle) * SHAKE_DISTANCE) + naturalLocation.x);
34 dialog.setLocation(shakenX, naturalLocation.y);
35 dialog.repaint();
36
37 int SHAKE_DURATION = 1000;
38 if (elapsed >= SHAKE_DURATION)
39 stopShake();
40 }
41 });
42 shakeTimer.start();
43 }
44
45 public void stopShake() {
46 shakeTimer.stop();
47 dialog.setLocation(naturalLocation);
48 dialog.repaint();
49 }
50
51 public static void main(String[] args) {
52 JOptionPane pane = new JOptionPane("your message",JOptionPane.ERROR_MESSAGE, JOptionPane.OK_OPTION);
53 JDialog d = pane.createDialog(null, "title");
54 Main dec = new Main(d);
55 d.pack();
56 d.setModal(false);
57 d.setVisible(true);
58 dec.startShake();
59 }
60 }
posted @ 2010-05-23 15:34  可微  阅读(1086)  评论(0)    收藏  举报