简体   繁体   中英

Java keypressed event not firing

During writing this code I realized if making into a jar there would have to be a graceful way to close the program. I have chosen to use the key 'F1'. I've researched a few articles online and found that the way I'm trying to handle it should be a viable approach, but the program doesn't even seem to fire the event method. The system.out.println never displays.

import java.applet.Applet;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;


public class MouseMove extends Applet implements KeyListener{

public static Random randomGenerator = new Random();
public static int code;

public void init(){
    addKeyListener(this);
}

public void keyPressed(KeyEvent evt){
    code = evt.getKeyCode();
    System.out.println("Key: "+KeyEvent.getKeyText(code));

    if(code == KeyEvent.VK_F1){
        System.exit(0);
    }
}

public void keyTyped(KeyEvent e){   
}
public void keyReleased(KeyEvent e){
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {

        Robot robot = new Robot();          

        while(true){

            robot.mouseMove((int)(Math.random()*1366), (int)(Math.random()*768));
            robot.delay(5000);
            robot.mouseWheel((int)(Math.random()*786));
            robot.delay(5000);
        }
    } catch (AWTException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}//main

}//class
  1. KeyListener works only if Component has Focus in the Window.

  2. You have to create a visible Container.

  3. setFocusable() for Component

  4. Better would be use Swing JComponent .

  5. Use JFrame instead of JApplet .

You never make an instance of MouseMove . Your main method just makes the robot and starts looping. If the object doesn't exists, one of it's methods can never be called.

Don't use System.exit() when you working with applets. Take a look at Java Applet (tutorial). You need to create .htm document and add <applet> tag to run an applet. You may use AppletViewer tool or web-browser to launch that htm document.

file.htm

<applet code="MouseMove" width="200" height="200"></applet>

start Appletviewer tool from command-line or open .htm in web-browser.

>appletviewer file.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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