// Fig. 10.24: Key.java
// Demonstrating keystroke events.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class Key extends Applet implements KeyListener, FocusListener {
  private String line1 = "";
  private String line2 = "";
  private String line3 = "";
  private TextArea editField;

  public void init()
  {
    editField = new TextArea("foo", 5, 40);
    // allow applet to process Key events
    editField.addKeyListener( this );
    editField.addFocusListener( this );

    add(editField);

    // make applet the active component for key events
    //requestFocus();
  }

  public void paint( Graphics g )
  {
    g.drawString( line1, 25, 25 );
    g.drawString( line2, 25, 40 );
    g.drawString( line3, 25, 55 );
  }

  public void keyPressed( KeyEvent e )
  {
    line1 = "Key pressed: " +
      e.getKeyText( e.getKeyCode() );
    setLines2and3( e );
  }

  public void keyReleased( KeyEvent e )
  {
    line1 = "Key released: " +
      e.getKeyText( e.getKeyCode() );
    setLines2and3( e );
  }

  public void keyTyped( KeyEvent e )
  {
    line1 = "Key typed: " + e.getKeyChar();
    System.out.println(line1);
    setLines2and3( e );
  }

  private void setLines2and3( KeyEvent e )
  {
    line2 = "This key is " +
      ( e.isActionKey() ? "" : "not " ) +
      "an action key";

    String temp = 
      e.getKeyModifiersText( e.getModifiers() );

    line3 = "Modifier keys pressed: " +
      ( temp.equals( "" ) ? "none" : temp );
    repaint();
    //    requestFocus();
  }

  public void focusGained( FocusEvent e ) {
    System.out.println("Got focus");
  }

  public void focusLost( FocusEvent e ) {
    System.out.println("Lost focus");
  }
}
