0

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) {

    }
   */
}
ExtremeSwat
  • 794
  • 1
  • 12
  • 34
  • 2
    Implementing a KeyListener doesn't mean your program is using it. You have to [add it to your applet](http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#addKeyListener(java.awt.event.KeyListener)). – BackSlash Apr 03 '14 at 08:05
  • @BackSlash might as well make that an answer – Paul Samsotha Apr 03 '14 at 08:06
  • Wait a moment, trying to understand it. I had a similar code that was working like that. Hmm..lemme try to check this out then I'll make you the guy who correctly answered me – ExtremeSwat Apr 03 '14 at 08:08
  • 1) Why code an applet? If it is due to spec. by teacher, please refer them to [Why CS teachers should stop teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why AWT rather than Swing? See my answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. – Andrew Thompson Apr 04 '14 at 05:07

1 Answers1

1

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);
    }
}
BackSlash
  • 21,927
  • 22
  • 96
  • 136