
Earthquake Dialog #38
Chapter 5, Windows, Dialogs, and Frames
|
201
HACK
So, that’s what happens in the actionPerformed( ) callback. The method
takes the elapsed time and figures out how far into a cycle it is (given a cycle
time of
SHAKE_CYCLE
), expressed as a
double
between
0
and
1
. Multiply this
by
2π
, and you’ve got an angle you can pass to
Math.sin( )
. Multiply that by
SHAKE_DISTANCE
, and you’ll have an x-offset in the range -
SHAKE_DISTANCE
≤
n
≤
SHAKE_DISTANCE
. Add that to the
naturalLocation
’s x-value, keep the natural
y-value, and you have the new location for the dialog. Call
setLocation( )
with this point and repaint( ).
actionPerformed( )
’s only other responsibility is to check to see if the anima-
tion time has expired and, if so, to call the
stopShake( ) method, which is
public and could thus be called by an outsider to end the animation prema-
turely.
stopShake( ) stops the Timer, returns the dialog to its natural loca-
tion, and
repaint( )s.
Shake, Rattle, and Roll
I’ve provided a main( ) method to demonstrate the DialogEarthquakeCenter.
To show its flexibility, I made it shake a
JOptionPane dialog, to prove you
can still use option dialogs as well as normal dialogs, although you do need
to work with option dialogs slightly differently:
public static void main (String[] args) {
JOptionPane pane =
new JOptionPane ("You've totally screwed up your login\n" +
"Go back and do it again... and do you think\n" ...