It is quite easy to change the mouse cursor in a Java Swing application, but most documentation and examples available only demonstrate how to change the cursor for a specific component. However, in an application I am developing – which has a fairly complex component hierarchy – I needed to ensure that the cursor would remain the one I set no matter where the mouse were (the most common example is the “busy / waiting” cursor, although that was not my case).
To change the cursor in a application wide fashion, you have to access the Glass Pane and set its cursor, and then make the glass pane visible – otherwise, it has no effect at all.
Take the following code as example:
int cursorType = Cursor.S_RESIZE_CURSOR; Component glassPane = ((RootPaneContainer)someComponent.getTopLevelAncestor()).getGlassPane(); glassPane.setCursor(Cursor.getPredefinedCursor(cursorType)); glassPane.setVisible(cursorType != Cursor.DEFAULT_CURSOR);
In the previous code, “someComponent” is any JComponent you have, it doesn’t matter which one (can be a JLabel, JButton, JPanel.. just take one). The trick is to access the RootPaneContainer, and then get the glass pane from it.
The last part is to make the glass pane visible only when the cursor is not the default one. That’s all.