How to change the mouse cursor in java?

痴心易碎 提交于 2019-11-29 01:41:23

问题


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?


回答1:


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) {
    }
});



回答2:


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




回答3:


You can also add MouseListener to the jList (or any ui component). Then implement the methods that 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));
                    }
                });


来源:https://stackoverflow.com/questions/7359189/how-to-change-the-mouse-cursor-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!