Keyboard Listener Application
<< Basic Starter Application | Applications | Image Movement Application >>
import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; import javax.swing.JPanel; public class KeyListenerApplication extends JPanel implements KeyListener { public static int WIDTH=800; public static int HEIGHT=600; private Font titleFont, regularFont; private int keyCode; private char c; public KeyListenerApplication() { //initialize variables here... titleFont = new Font("Roman", Font.BOLD, 18); regularFont = new Font("Helvetica", Font.PLAIN, 12); keyCode=0; c='-'; } public static void main(String[] args) { KeyListenerApplication app= new KeyListenerApplication(); JFrame window = new JFrame("Type a Key to See Its Code"); window.setSize(WIDTH, HEIGHT); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.getContentPane().add(app); window.addKeyListener(app); //window.pack(); window.setVisible(true); } public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Color.WHITE); g.fillRect(0, 0, getWidth(),getHeight()); g.setColor(Color.BLUE); g.setFont(titleFont); g.drawString("Type a Key to See Its Code", 20, 20); g.setColor(Color.BLACK); g.setFont(regularFont); g.drawString("Version 1.0", 20, 40); g.drawString("the key char "+c+" has code "+keyCode, 20, 60); g.setFont(new Font("Arial", Font.PLAIN, 48)); g.setColor(Color.red); g.drawString("\""+c+"\"",80, 120); } // update is a workaround to cure Windows screen flicker problem public void update(Graphics g){ paint(g); } // These 3 methods need to be declares to implement the KeyListener Interface @Override public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) { keyCode=e.getKeyCode(); c=e.getKeyChar(); repaint(); } @Override public void keyReleased(KeyEvent e) {} }