title: Keyboard input in Java Applet
body: <p>What is the best way to listen for keyboard input in a Java Applet?</p>
  
  <p>I have an applet which opens a JFrame and I am using a KeyListener to listen for keyboard input. This works fine in my development environment (eclipse), but when I run the applet through a browser (I have tried Firefox and IE) it does not respond to keyboard events.
  However, if I run the applet and then minimize and maximize the frame, it works.
  I have tried setting focus to the JFrame in many different ways and also programmatically minimizing and maximizing it, but to no effect.
  I have also tried key bindings, but with the same problem.</p>
  
  <p>I have trimmed my code down to the barest essentials of the problem and pasted it below.
  Can someone see what I am doing wrong or suggest a better solution?</p>
  
  <pre><code>public class AppletTest extends Applet 
  {    
      private GuiTest guiTest; 
  
      public void init() {
          guiTest = new GuiTest();
          final AppletTest at = this;
          guiTest.addKeyListener(new KeyListener() {
              public void keyPressed(KeyEvent ke) {
                  at.keyPressed(ke);
              }
              public void keyReleased(KeyEvent ke) {}
              public void keyTyped(KeyEvent e) {}             
          });
      }
  
      private void keyPressed(KeyEvent ke)
      {
          System.out.println("keyPressed "+KeyEvent.getKeyText(ke.getKeyCode()));
          getGuiTest().test(KeyEvent.getKeyText(ke.getKeyCode()));
      }
  }
  
  public class GuiTest extends JFrame {
      String teststring = "?";
      public GuiTest()
      {
          setSize(100,100);
          setEnabled(true);
          setVisible(true);
          setFocusable(true);
          requestFocus();
          requestFocusInWindow();
          toFront();
      }
  
      public void test(String t)
      {
          teststring = t;
          repaint();
      }
  
      public void paint(Graphics g)
      {
          g.setColor(Color.white);
          g.fillRect(0, 0, getWidth(), getHeight());
          g.setColor(Color.black);
          g.drawString(teststring, 50, 50);
      }
  }
  </code></pre>