gpt4 book ai didi

java:鼠标悬停时模拟按键并按住

转载 作者:行者123 更新时间:2023-12-01 09:45:54 26 4
gpt4 key购买 nike

我试图在鼠标位于按钮顶部时模拟按键并按住(在java中)。仅当鼠标不再位于按钮上方时,按键才应停止。我的按键可以工作,但不能按住它。做这个的最好方式是什么?我尝试了永无休止的循环,但当鼠标退出时它不会停止(显然)。

这是我的一些工作代码:

    buttonSD = new JButton("S+D");
buttonSD.addMouseListener(new MouseAdapter(){
public void mouseEntered(MouseEvent e){
CoordsLabel.setText("Bottom Right");
currentBtn.keyPress(KeyEvent.VK_S);
currentBtn2.keyPress(KeyEvent.VK_D);
}

public void mouseExited(MouseEvent e){
currentBtn.keyRelease(KeyEvent.VK_S);
currentBtn2.keyRelease(KeyEvent.VK_S);
}
});
c.weightx = .25;
c.weighty = .25;
c.gridx = 2;
c.gridy = 2;
gridbag.setConstraints(buttonSD, c);
controlFrame.add(buttonSD);

try{
currentBtn = new Robot();
currentBtn2 = new Robot();
} catch (AWTException e){
e.printStackTrace();
}

提前致谢!

最佳答案

So, he can use WASD with just a mouse over.

那么您可能想要做的是在 mouseEntered 事件上启动 Swing 计时器,然后在 mouseExited 事件上停止计时器。

当计时器触发时,您只需调用按钮的 doClick() 方法。

阅读 Swing 教程中关于 How to Use Swing Timer 的部分了解更多信息和工作示例。

您还可以查看:Update a Label with a Swing Timer举一个更简单的例子。

关于java:鼠标悬停时模拟按键并按住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38031929/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com