O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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" +
"you could remember your password this time?",
JOptionPane.ERROR_MESSAGE,
JOptionPane.OK_OPTION);
JDialog d = pane.createDialog (null, "Shakin'!");
DialogEarthquakeCenter dec = new DialogEarthquakeCenter (d);
d.pack( );
d.setModal (false);
d.setVisible(true);
dec.startShake( );
// wait (forever) for a non-null click and then quit
while (pane.getValue( ) == JOptionPane.UNINITIALIZED_VALUE ) {
try { Thread.sleep(100); }
catch (InterruptedException ie) {}
}
System.exit(0);
}
The main( ) method builds a JOptionPane dialog through what can only be
called “the other way.” Most developers will call
JOptionPane.show...
Dialog( )
because it’s convenient to get the dialog on screen immediately and
provide the user’s selection as a return value, and because it’s not necessary

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required