Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the mouse cursor in java?

I have a list of words inside the JList. Every time I point the mouse cursor at a word, I want the cursor to change into a hand cursor. Now my problem is how to do that?

Could someone help me with this problem?

like image 913
papski Avatar asked Sep 09 '11 08:09

papski


People also ask

How do I change the cursor type in Java?

We can change Swing's objects ( JLabel , JTextArea , JButton , etc) cursor using the setCursor() method. In the snippet below, for demonstration, we change the cursor of the JFrame . Your mouse pointer or cursor shape will be changed if you positioned inside the frame. A collections of cursor shape defined in the java.

How do I change the color of my cursor in Java?

put( "TextField. caretForeground" , Color. red ); Just put this code at the start of your main() (or anywhere before any GUIs are displayed), and it will set all the carets in all the textfields to red (or any other color you specify).


2 Answers

Use a MouseMotionListener on your JList to detect when the mouse enters it and then call setCursor to convert it into a HAND_CURSOR.

Sample code:

final JList list = new JList(new String[] {"a","b","c"}); list.addMouseMotionListener(new MouseMotionListener() {     @Override     public void mouseMoved(MouseEvent e) {         final int x = e.getX();         final int y = e.getY();         // only display a hand if the cursor is over the items         final Rectangle cellBounds = list.getCellBounds(0, list.getModel().getSize() - 1);         if (cellBounds != null && cellBounds.contains(x, y)) {             list.setCursor(new Cursor(Cursor.HAND_CURSOR));         } else {             list.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));         }     }      @Override     public void mouseDragged(MouseEvent e) {     } }); 
like image 170
dogbane Avatar answered Oct 11 '22 13:10

dogbane


You probably want to look at the Component.setCursor method, and use it together with the Cursor.HAND constant.

like image 31
aioobe Avatar answered Oct 11 '22 12:10

aioobe