|Developer's Daily||Java Education|
|front page | java | perl | unix | DevDirectory|
Recently I was asked how to turn the mouse pointer (cursor) into an hourglass symbol (using pure Java code) so users would know that the program was waiting on something. Though I haven't done this yet in a commercial application, it looks like it's pretty straightforward (only two lines of code or so), so here goes.
Using the Cursor class and setCursor() method
Assuming that you're working inside of a JFrame, all you have to do to change the shape of the cursor are two lines of code like this:
Cursor hourglassCursor = new Cursor(Cursor.WAIT_CURSOR);
To set the cursor back to it's "default" shape, just make this call:
Cursor normalCursor = new Cursor(Cursor.DEFAULT_CURSOR);
For the purposes of this tutorial, I've created a simple DemoClass, as you can see in Figure 1. Notice that the area I'm about to type in is highlighted in yellow (this actually comes from one of JBuilder's great OpenTools projects).
Also, before you start giving me grief about this code -- it's just demo code. I know that there are more efficient ways to code this in a production app, but for the purposes of a demo I thought this was the best approach.
Other cursor shapes
Once you get into it, you'll see that you can actually change the cursor to any of 13 different styles.
A list of the different possible shapes for a cursor are shown in the
class, and are also listed in Table 1.
|Constants for the shapes available in the
|Table 1:||Constants in the
For more details, either look at the source code for the
Cursor class (
java.awt.Cursor), or look at the Javadoc for the
A sample application
I've included a simple sample application that shows how this is done. The application includes two buttons, and pressing on the buttons changes the cursor. This is shown in Figure 1.
|Figure 1:||The simple application includes two buttons for changing the cursor's appearance.|
Download the sample code
You can download the source code for this simple application by clicking the link below. You'll see some auto-generated JBuilder code in the source, but don't let that stop you from seeing how easily the cursor shape is modified.
Download the sample source code.
Changing the shape of the mouse cursor appears to be very easy. Just use the
class, and the
setCursor() method, and you are ready to go.
I hope you've found this article helpful. Send me a note if you'd like to add something to this article, or if you'd like to see an article written about another topic.
Copyright © 2002 DevDaily Interactive, Inc.
All Rights Reserved.