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

444
|
Chapter 12, Miscellany
#88 Display a Busy Cursor
HACK
First, you need to build an AnimatedCursor class and generate the images in
the constructor. In this case, the images are instances of the
java.awt.Cursor
object. I used standard, predefined cursors to keep the code easy, but you
could also use cursors derived from custom images. A
JFrame
is passed into
the constructor and stored for later use, as you can see in Example 12-1.
AnimatedCursor implements Runnable because it will be threaded, and it
accepts action events to turn on and off the animation. You can reuse the
standard directional cursors, one for each compass direction, stored in a
Cursor array, which is eight items long.
Running the Animation
Next, you need to build the actual animation thread:
public void run( ) {
int count = 0;
while(animate) {
try {
Thread.currentThread( ).sleep(200);
} catch (Exception ex) { }
frame.setCursor(cursors[count % cursors.length]);
count++;
}
frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
Example 12-1. A simple animated cursor
public class AnimatedCursor implements Runnable, ActionListener {
private boolean animate;
private Cursor[] cursors;
private JFrame frame;
public AnimatedCursor(JFrame frame) {
animate = false;
cursors = new Cursor[8];
this.frame = frame;
cursors[0] = Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR);
cursors[1] = Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR);
cursors[2] = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
cursors[3] = Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR);
cursors[4] = Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR);
cursors[5] = Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR);
cursors[6] = Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR);
cursors[7] = Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR);
}
}

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