简体   繁体   中英

Java Applet with Keylistener not working

I have a problem with my problem. I am currently playing around with KeyListener in a Java applet, the problem is nothing happens when I type a key(No display). Here's the code :

package appl;

import java.applet.Applet;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Appl extends Applet implements KeyListener {

    @Override
    public void keyTyped(KeyEvent ke) {
        System.out.println("Pressed: " + ke.getKeyCode());
    }

    @Override
    public void keyPressed(KeyEvent ke) {
          System.out.println("Pressed: " + ke.getKeyChar());
    }

    @Override
    public void keyReleased(KeyEvent ke) {
          System.out.println("Pressed: " + ke.getKeyChar());
    }



   /* 
  public static void main(String[] args) {

    }
   */
}

Implementing a KeyListener doesn't mean your program is using it. You have to add it to your applet.

public class Appl extends Applet implements KeyListener {

    @Override
    public void keyTyped(KeyEvent ke) {
        System.out.println("Pressed: " + ke.getKeyCode());
    }

    @Override
    public void keyPressed(KeyEvent ke) {
          System.out.println("Pressed: " + ke.getKeyChar());
    }

    @Override
    public void keyReleased(KeyEvent ke) {
          System.out.println("Pressed: " + ke.getKeyChar());
    }



    public void init() {
        // YOUR CODE
        addKeyListener(this);
    }
}

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