简体   繁体   English

用Java中的KeyEvent中断for循环

[英]Break a for loop with a KeyEvent in java

How can I break a for loop (outside the listener) when a KeyEvent occur (pressed the S key) ? 发生KeyEvent(按S键)时,如何中断for循环(在侦听器外部)? I tried to do it but it doesn't work. 我尝试这样做,但是没有用。

This is the listener : 这是听众:

public class ListenKey implements KeyListener{

    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub
        if(e.getKeyCode()==KeyEvent.VK_S) 
            Spressed = true;
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub
        if(e.getKeyCode()==KeyEvent.VK_S) 
            Spressed = true;
    }

    @Override
    public void keyTyped(KeyEvent e) {
        if(e.getKeyCode()==KeyEvent.VK_S) 
            Spressed = true;
    }

}

And this is the for loop : 这是for循环:

for(int i=1; i<=times; i++) {
                    try {
                        Thread.sleep((int)(speed*1000));
                        (new Robot()).mouseMove((int)Math.abs(((r.nextInt())%(Toolkit.getDefaultToolkit().getScreenSize().getWidth())+1)), 
                                                (int)Math.abs(((r.nextInt())%(Toolkit.getDefaultToolkit().getScreenSize().getHeight())+1)));
                    } catch (InterruptedException | AWTException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                    if(Spressed == true) {
                        System.out.println("S");
                        Spressed = false;
                        break;  
                    }
                }

I am trying to create a program that make the mouse jump around, just for entertaining purpose :) but I want the users to be able to stop the mouse when they pressed the S key 我正在尝试创建一个程序,使鼠标跳动,仅用于娱乐目的:),但我希望用户在按S键时能够停止鼠标

A while loop usually works better for what you're trying to accomplish than a for loop. for循环相比, while循环通常可以更好地完成您要完成的任务。 Assuming that your class sets Spressed to false before the loop, here's what the code would be: 假设您的类在循环之前将Spressed设置为false,则代码如下所示:

while (!Spressed) {
    try {
        Thread.sleep((int)(speed*1000));
        (new Robot()).mouseMove((int)Math.abs(((r.nextInt())%(Toolkit.getDefaultToolkit().getScreenSize().getWidth())+1)), 
        (int)Math.abs(((r.nextInt())%(Toolkit.getDefaultToolkit().getScreenSize().getHeight())+1)));
    } catch (InterruptedException | AWTException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}
System.out.println("S");
Spressed = false;
break;

Also, you should follow Java variable naming conventions and call it sPressed instead of Spressed . 另外,您应该遵循Java变量命名约定,并将其命名sPressed而不是Spressed

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

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