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);
}
}

Get Swing Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.