How to change cursor icon in Java?

2019-01-17 11:07发布

问题:

I would like to change the cursor icon to my customized 32x32 image when a Java application is executing. I looked and searched, those I found are just setting cursor on a JComponent. But I want the cursor changed to my specified icon wherever it goes moving, browsing, and click, as long as the Java application is still running, or you can say program runtime.

Thanks alot.

回答1:

Standard cursor image:

setCursor(Cursor.getDefaultCursor());

User defined Image:

Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image = toolkit.getImage("icons/handwriting.gif");
Cursor c = toolkit.createCustomCursor(image , new Point(mainPane.getX(), 
           mainPane.getY()), "img");
mainPane.setCursor (c);

You can download a zip containing sample source: HERE



回答2:

Call Component.setCursor. The class Cursor as a few predefined cursors.

A custom cursor image can be created:

setCursor(Toolkit.getDefaultToolkit().createCustomCursor(
new ImageIcon("custom.png").getImage(),
new Point(0,0),"custom cursor"));


回答3:

Try settin the cursor on the rootPane.

frame.getRootPane().setCursor(...);


回答4:

public void mouseEntered(MouseEvent e)
{
// set cursor for frame and its component
//  this is the current frame you are using .
//  You can change the this keyword with your frame name .

java.awt.Toolkit toolkit = java.awt.Toolkit.getDefaultToolkit();
Image image = toolkit.getImage("/images/mousepoint.jpg");
Cursor a = toolkit.createCustomCursor(image , new Point(this.getX(),this.getY()), "");
this.setCursor (a);
}

or you can refer to :-
http://java23s.blogspot.in/2011/07/to-change-mouse-pointer-using-java.html



回答5:

Why don't you have a class MyFrame which exteds JFrame. All it does is call the JFrame constructor and sets the cursor to your desired cursor. In my application we have a touch screen with no cursor so this is how I intend to implement it.