Search code examples
javaeventscursor

Java: does a mouseMoved event and a button.addMouseListener interfere?


Now I am using the following code to draw a cursor (with a greater size):

Cursor emptyCursor = Toolkit.getDefaultToolkit().createCustomCursor(new BufferedImage(12, 12, BufferedImage.TYPE_INT_ARGB), new Point(0, 0), "empty"); 
        setCursor(emptyCursor);

        Toolkit toolkit = Toolkit.getDefaultToolkit();

        final long eventMask = AWTEvent.MOUSE_MOTION_EVENT_MASK + AWTEvent.MOUSE_EVENT_MASK + AWTEvent.KEY_EVENT_MASK;
        final ImageIcon icon = createImageIcon("images/cursor.png");
        cursorLabel = new JLabel(icon);

        toolkit.addAWTEventListener(new AWTEventListener() {
            public void eventDispatched(AWTEvent e) {
                MouseEvent  me=(MouseEvent)e;
                cursorLabel.setLocation(me.getLocationOnScreen().x, me.getLocationOnScreen().y);
            }
        }, eventMask);

        layeredPane = this.getLayeredPane();  
        if (icon != null) {
            cursorLabel.setBounds(15, 225, icon.getIconWidth(), icon.getIconHeight());
        } else {
            System.err.println("Cursor Icon not found!");
        }
        layeredPane.add(cursorLabel);

Afterwards I used the following code for the button:

button.addMouseListener(new MouseListener(){
                public void mouseClicked(MouseEvent arg0) {
                }
                public void mouseEntered(MouseEvent arg0) {
                    button.setBackground(Color.yellow);
                }
                public void mouseExited(MouseEvent arg0) {
                    button.setBackground(Color.white);
                }
                public void mousePressed(MouseEvent arg0) {
                }
                public void mouseReleased(MouseEvent arg0) {
                } 
            });

The cursor works fine, but only if I don't press the button, because than it's drawn under the button.. What's the problem?


Solution

  • Buttons have their own MouseListener to handle rollover effects. So the MouseEvent is only passed to the button and not the layered pane.

    Maybe you can use an AWTEventListener to listen for your mouse events. See Global Event Listeners for more information.