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

/* Cursor.CROSSHAIR_CURSOR is predefined */
Cursor curse = new Cursor(Cursor.CROSSHAIR_CURSOR); //or...
Cursor curse = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);

You set the cursor of any Swing Component using the setCursor() method.

/* You can use setCursor() on almost any
 * Swing Component, including JPanel,
 * JButton etc. even JFrame */
JPanel myPanel = new JPanel();
myPanel.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR);

Here is a sample program:

import java.awt.*;
import javax.swing.*;

public class MainApp extends JFrame{
	
	public MainApp(){
		
		// Chores
		setSize(400,400);
		setVisible(true);
		
		// Set a Predefined Cursor to our JFrame
		setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
	}
	
	public static void main(String[] args){
		// For Native Look and Feel
		try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
		}catch(Exception e){}
		
		/* Run the Frame */
		SwingUtilities.invokeLater(new Runnable(){
			public void run(){
				new MainApp();
			}
		});
	}

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s