[英]Java mouse hover event while left mouse key is pressed
In a panel I've got 10*10 togglebutton. 在面板中,我有10 * 10切换按钮。 My goal is to do this event: If left mouse key is down and the mouse is over the specific button call "click on the button" line. 我的目标是执行此事件:如果鼠标左键按下并且鼠标在特定按钮上,则调用“单击按钮”行。 So the user can select (click on) multiple buttons easily. 因此,用户可以轻松选择(单击)多个按钮。
This is not working (changing the same button instead of changing anothers when the mouse is moved): 这不起作用(移动鼠标时,更改同一按钮而不是更改其他按钮):
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);
}
});
}
}
Tried this, not working (what is wrong with his implementation?): 尝试了一下,不起作用(他的实现有什么问题?):
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 );
}
}
});
}
}
The source of the mouseDragged event will always be the component where you first generated the mousePressed event, even if you move the mouse over another component. 即使将鼠标移到另一个组件上,mouseDragged事件的来源也始终是您首次生成mousePressed事件的组件。
If you want to know what component the mouse is currently over then you will need to do some extra work. 如果您想知道鼠标当前位于哪个组件上,则需要做一些额外的工作。
Something like: 就像是:
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 );
}
The above code attempts to convert the mouse location on the screen to find the component it is currently over. 上面的代码尝试转换鼠标在屏幕上的位置,以查找当前位于其上方的组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.