Java Notes


Sometimes you want to change the cursor to show the user that something is different. For example, you might want to show a wait cursor (typically an hour glass or watch) when the program is working on something that will take a long time. Or you might want to change to a crosshairs cursor when the user must indicate a pixel to draw on.

The cursor is attached to a component

A change in the cursor occurs only when it is over the component that has set it. If you want to set the cursor for the whole window (JFrame), you need to set it for the content pane of the window.

Using the java.awt.Cursor class

You will need to import java.awt.Cursor.

The predefined cursors

There are a number of predefined cursors. Java has names for each of the predefined cursors, but the exact appearance of each cursor depends on the system that it is running on. Eg you may see the wait cursor as an hourglass in Windows, and as a wristwatch on the Macintosh (See Look and Feel).

These predefined constants in the Cursor class are not cursors, they are int codes that are used as a parameter in the Cursor.getPredefinedCursor(int) method.

int typedescription
Cursor.DEFAULT_CURSORdefault cursor
Cursor.CROSSHAIR_CURSORcrosshair cursor
Cursor.HAND_CURSORhand cursor
Cursor.MOVE_CURSORmove cursor
Cursor.WAIT_CURSORwait cursor
Cursor.TEXT_CURSORtext cursor
Cursor.E_RESIZE_CURSOReast-resize cursor
Cursor.N_RESIZE_CURSORnorth-resize cursor
Cursor.NE_RESIZE_CURSORnorth-east-resize cursor
Cursor.NW_RESIZE_CURSORnorth-west-resize cursor
Cursor.S_RESIZE_CURSORsouth-resize cursor
Cursor.SE_RESIZE_CURSORsouth-east-resize cursor
Cursor.SW_RESIZE_CURSORsouth-west-resize cursor
Cursor.W_RESIZE_CURSORwest-resize cursor

The Container setCursor(. . .) method

After you call a component's setCursor(...) method, the cursor will be changed. The parameter to setCursor(. . .) is a Cursor object. You can create your own cursors, but you will probably be satisfied using the predefined cursors.

Example - Setting the wait cursor for a frame (window)

   Container c = frame.getContentPane();  // get the window's content pane
   . . . // do something that takes a long time

Custom and other system cursors

You can create your own cursors (see Toolkit.createCustomCursor()) or use cursors from the local system (see Cursor.getSystemCustomCursor(String)).