Changing Cursors in Java Swing

OK then. Let’s get started. This tutorial will teach you how to change the cursor icon which is used to display the location of the mouse, to one of the other predefined Icons in the Java Abstract Window Toolkit (and hence, Java Swing).
You change the cursor using

1/* Cursor.CROSSHAIR_CURSOR is predefined */
2Cursor curse = new Cursor(Cursor.CROSSHAIR_CURSOR); //or...
3Cursor curse = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
You set the cursor of any Swing Component using the setCursor() method.

1/* You can use setCursor() on almost any
2 * Swing Component, including JPanel,
3 * JButton etc. even JFrame */
4JPanel myPanel = new JPanel();
5myPanel.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR);
Here is a sample program:

01import java.awt.*;
02import javax.swing.*;
03 
04public class MainApp extends JFrame{
05     
06    public MainApp(){
07         
08        // Chores
09        setSize(400,400);
10        setVisible(true);
11         
12        // Set a Predefined Cursor to our JFrame
13        setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
14    }
15     
16    public static void main(String[] args){
17        // For Native Look and Feel
18        try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
19        }catch(Exception e){}
20         
21        /* Run the Frame */
22        SwingUtilities.invokeLater(new Runnable(){
23            public void run(){
24                new MainApp();
25            }
26        });
27    }
28 
29}

No comments:

Post a Comment