[英]How to change the mouse cursor in java?
I have a list of words inside the JList. 我在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? 有人可以帮我解决这个问题吗?
Use a MouseMotionListener on your JList to detect when the mouse enters it and then call setCursor
to convert it into a HAND_CURSOR
. 在JList上使用MouseMotionListener来检测鼠标何时进入它,然后调用
setCursor
将其转换为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) {
}
});
您可能希望查看Component.setCursor
方法,并将其与Cursor.HAND
常量一起使用。
You can also add MouseListener
to the jList (or any ui component). 您还可以将
MouseListener
添加到jList(或任何ui组件)。 Then implement the methods that mouseEntered
, mouseExited
然后实现
mouseEntered
, mouseExited
的方法
jList.addMouseListener(new MouseListener() {
@Override
public void mouseEntered(MouseEvent e) {
cw.list.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
}
@Override
public void mouseExited(MouseEvent e) {
cw.list.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.