0 Replies Latest reply: Nov 13, 2013 11:03 AM by 435b0fb4-9c6c-4b12-9d1d-fcb6e057c870 RSS

    addKeyListener does not work

    435b0fb4-9c6c-4b12-9d1d-fcb6e057c870

      I copied this sample program and expected the window to be closed after pressing any key but it does not work. Why?

       

      /* Listing2702_EinEinfacherBildschirmschoner.java */

      import java.awt.*;
      import java.awt.event.*;


      public class Listing2702_EinEinfacherBildschirmschoner
      extends Window
      {
      public static void main(String[] args)
      {
        final Listing2702_EinEinfacherBildschirmschoner wnd = new Listing2702_EinEinfacherBildschirmschoner();
        wnd.setLocation(new Point(500,200));
        wnd.setSize(500,200);
        wnd.requestFocus();
        wnd.setVisible(true);
        wnd.addKeyListener(
          new KeyAdapter() {
           public void keyTyped(KeyEvent event)
           {   
            wnd.setVisible(false);
            wnd.dispose();
            System.exit(0);
           }
          }
          );

      }

      public Listing2702_EinEinfacherBildschirmschoner()
      {
        super(new Frame());
        setBackground(Color.black);
      }

      public void paint(Graphics g)
      {
        g.setColor(Color.red);
        g.drawString(
          "Screen size is "+
            getSize().width+"*"+getSize().height,
            10,
            20
          );
        g.drawString("Press any key",10,40);
      }
      }