import java.awt.*;
import java.awt.Event;
import javax.swing.*;
import java.awt.event.*;

public class KeyExample extends JFrame {
  public class KeyCanvas extends JPanel {
      protected String value = "";
      protected String message = "Hit any character key. It will be echoed below";
      protected Font messageFont = new Font("Helvetica", Font.PLAIN, 20);
      protected Font keyFont = new Font("Helvetica", Font.BOLD, 64);

    public void paintComponent(Graphics gr) {
	Graphics g = gr.create();
	int windowWidth = getSize().width;
	int windowHeight = getSize().height;
	FontMetrics keyfm = g.getFontMetrics(keyFont);

	super.paintComponent(g);
	g.setFont(messageFont);
	g.drawString(message, 10, 30);
	g.drawLine(0, windowHeight/ 2, 
		   windowWidth, windowHeight / 2);
	g.setFont(keyFont);
	g.drawString(value, windowWidth / 2 - keyfm.stringWidth(value) / 2, 
		     windowHeight * 3 / 4 + keyfm.getHeight() / 2);
    }

    //If we don't specify this, the canvas might not show up at all
    //(depending on the layout manager).
    public Dimension getPreferredSize() {
	Graphics g = getGraphics();
	FontMetrics fm = g.getFontMetrics(messageFont);
        return new Dimension(fm.stringWidth(message) + 20, 
			     300);
    }

    public KeyCanvas() {
      addKeyListener(new KeyAdapter() {
	public void keyTyped(KeyEvent e) {
	  value = value + e.getKeyChar();
	  repaint();
	}
      });
      addMouseListener(new MouseAdapter() {
	      public void mouseEntered(MouseEvent e) {
		  ((JPanel)e.getSource()).requestFocus();
	      }
	  });

    }      
  }
  public static void main(String args[]) {
    KeyExample app = new KeyExample("Key Listener Application");
    app.pack();
    app.setVisible(true);
  }
  public KeyExample(String frameTitle) {
    super(frameTitle);
    KeyCanvas key_canvas = new KeyCanvas();
    getContentPane().add (key_canvas);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
}