简体   繁体   English

Java:mouseMoved事件和button.addMouseListener是否会干扰?

[英]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? 光标可以正常工作,但是仅当我不按按钮时才起作用,因为它比按钮下方绘制的要好。问题是什么?

Buttons have their own MouseListener to handle rollover effects. 按钮具有自己的MouseListener来处理翻转效果。 So the MouseEvent is only passed to the button and not the layered pane. 因此,MouseEvent仅传递给按钮,而不传递给分层窗格。

Maybe you can use an AWTEventListener to listen for your mouse events. 也许您可以使用AWTEventListener侦听鼠标事件。 See Global Event Listeners for more information. 有关更多信息,请参见全局事件监听器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM