Java Swing FAQ: How do I create a wait cursor in a Java application?
I was going to write a nice, complicated Java “wait cursor” example today, showing you how to create an animated wait cursor in Java using threads, but after looking at a much simpler approach, I've decided to show that instead.
Java wait cursor example class
Here's the source code for an example class that shows how to create a Java wait cursor (also known as a "busy cursor"). This is a very simple example that demonstrates how to toggle back and forth between a wait cursor and the default cursor. Here's the code:
import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * A simple Java wait cursor example. * @author Alvin Alexander, devdaily.com */ public class JavaWaitCursorExample implements ActionListener { private JFrame frame; private String defaultButtonText = "Show Wait Cursor"; private JButton button = new JButton(defaultButtonText); private Cursor waitCursor = new Cursor(Cursor.WAIT_CURSOR); private Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR); private boolean waitCursorIsShowing; public static void main(String[] args) { new JavaWaitCursorExample(); } public JavaWaitCursorExample() { // our class is the actionlistener on the button button.addActionListener(this); // note: this should be inside a SwingUtilities.invokeLater call. // see: http://devdaily.com/java/jframe-example frame = new JFrame("Java Wait Cursor Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(button); frame.setPreferredSize(new Dimension(400,300)); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public void actionPerformed(ActionEvent evt) { if (waitCursorIsShowing) { // set the cursor back to the default waitCursorIsShowing = false; button.setText(defaultButtonText); frame.setCursor(defaultCursor); } else { // change the cursor to the wait cursor waitCursorIsShowing = true; button.setText("Back to Default Cursor"); frame.setCursor(waitCursor); } } }
I was also going to share some screenshots here, but creating a screenshot that also includes the cursor proved to be a more difficult task than I want to tackle today, so I'm going to have leave it at (a) it works fine on my Mac OS X 10.5 computer, and (b) please run this code on your system to see what it looks like there.
Also, if you have any questions about how this Java cursor approach works, just let me know, otherwise I'm leaving this without any more discussion today.