按下鼠标左键时Java鼠标悬停事件

时间:2018-08-18 20:54:24

标签: java swing keyevent

在面板中,我有10 * 10切换按钮。我的目标是参加此活动: 如果鼠标左键按下并且鼠标悬停在特定按钮上,则调用“单击按钮”行。因此,用户可以轻松选择(单击)多个按钮。

这不起作用(在移动鼠标时更改相同的按钮,而不是更改另一个按钮):

import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.JToggleButton;

public class ButtonClickOnHover {
    public void clickOnButtonOnHover(JToggleButton button) {
        button.addMouseMotionListener(new MouseMotionListener() {

            @Override
            public void mouseMoved(MouseEvent e) {

            }

            @Override
            public void mouseDragged(MouseEvent e) {
                button.doClick(0);
            }

        });
    }
}

试过这个,不起作用(他的实现有什么问题?):

import java.awt.Color;
import java.awt.Component;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;

public class ButtonClickOnHover {
    public void clickOnButtonOnHover(JPanel panel) {
        panel.addMouseMotionListener(new MouseMotionListener() {



    @Override
    public void mouseMoved(MouseEvent e) {

    }

    @Override
    public void mouseDragged(MouseEvent e) {
        Point location = MouseInfo.getPointerInfo().getLocation();
        JPanel parent = (JPanel) e.getComponent();
        SwingUtilities.convertPointFromScreen(location, parent);
        Component mouseOver = parent.findComponentAt( location );

        if (mouseOver instanceof JToggleButton)
        {
            JToggleButton button = (JToggleButton)mouseOver;
            button.setBackground( Color.YELLOW );
        }
    }

});

}
}

1 个答案:

答案 0 :(得分:2)

即使将鼠标移到另一个组件上,mouseDragged事件的源也始终是您首次生成mousePressed事件的组件。

如果您想知道鼠标当前位于哪个组件上,则需要做一些额外的工作。

类似的东西:

Point location = MouseInfo.getPointerInfo().getLocation();
Component button = e.getComponent();
JPanel parent = (JPanel)button.getParent();
SwingUtilities.convertPointFromScreen(location, parent);
Component mouseOver = parent.findComponentAt( location );

if (mouseOver instanceof JToggleButton)
{
    JToggleButton button = (JToggleButton)mouseOver;
    button.setBackground( Color.YELLOW );
}

上面的代码尝试转换鼠标在屏幕上的位置,以查找当前位于其上方的组件。