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

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.

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