Display a Busy Cursor #88
Chapter 12, Miscellany
|
445
HACK
Like most run( ) methods, the previous code does something repeatedly in a
loop with a
sleep( ) on each pass. In this case, you call setCursor( ) on the
frame and increment the count variable. Notice the code line:
cursors[count % cursors.length]
which will loop over each cursor in the array, wrapping when it reaches the
end. The mod operator (
%) is indispensable for these types of calculations.
The loop also sleeps on every pass. I chose 200 ms because that lets the
cursor make a complete revolution every second and a half, which seemed
about right; you can adjust it to your taste:
public void actionPerformed(ActionEvent evt) {
JButton button = (JButton)evt.getSource( );
if(animate) {
button.setText("Start Animation");
animate = false;
} else {
animate = true;
button.setText("Stop Animation");
new Thread(this).start( );
}
}
The actionPerformed( ) method starts and stops the animation thread. It
also updates the text on the
JButton as further user feedback.
Put It All Together
public static void main(String[] args) {
JFrame frame = new JFrame("Animated Cursor Hack");
JButton button = new JButton("Start Animation");
button.addActionListener(new AnimatedCursor(frame));
frame.getContentPane( ).add(button);
frame.pack( );
frame.show( );
}
The main( ) method in the preceding code creates a frame with a control but-
ton. The
AnimatedCursor applies directly to the frame so that the cursor will
animate whenever it’s over the window. A screen capture cannot really cap-
ture the effect, but when you put it together, it will look something like
Figure 12-1.

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.