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(Font.SANS_SERIF, Font.PLAIN, 20); protected Font keyFont = new Font(Font.SANS_SERIF, Font.BOLD, 64); public void paintComponent(Graphics g) { super.paintComponent(g); int windowWidth = getSize().width; int windowHeight = getSize().height; FontMetrics keyfm = g.getFontMetrics(keyFont); 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() { // requestFocusInWindow gives a component keyboard focus. The // Java documentation suggests using requestFocusInWindow // rather than requestFocus, because requestFocus's behavior // is platform dependent public void mouseEntered(MouseEvent e) { ((JPanel)e.getSource()).requestFocusInWindow(); } }); } } 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); } }