繁体   English   中英

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

[英]java: Simulate keypress and hold while mouse hovers

我试图模拟鼠标按住按钮(在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();
    }

提前致谢!

因此,他只需滑过鼠标即可使用WASD。

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

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

阅读Swing教程中有关如何使用Swing计时器的部分, 获取更多信息和工作示例。

您也可以签出:使用更简单的示例,使用Swing计时器更新标签

触发MouseEvent e 要模拟按键保持,只需添加一次名为toggle的变量来表示保持状态,并向每个函数添加一个保护子句,就可以仅发送一次keyPress

bool toggle = 0;

public void mouseEntered(MouseEvent e){
        if (toggle == 0) {
            CoordsLabel.setText("Bottom Right");
            currentBtn.keyPress(KeyEvent.VK_S);
            currentBtn2.keyPress(KeyEvent.VK_D);
            toggle = 1;
        }
    }


public void mouseExited(MouseEvent e){
        if (toggle == 1) {
            CoordsLabel.setText("RELEASED");
            currentBtn.keyRelease(KeyEvent.VK_S);
            currentBtn2.keyRelease(KeyEvent.VK_S);
        } else {
            CoordsLabel.setText("Nope");
        }
    }

暂无
暂无

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

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