Key event on frame : Key Event « Event « Java

Key event on frame

Key event on frame
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class SketchPanel extends JPanel implements KeyListener {

  private Point startPoint = new Point(0, 0);

  private Point endPoint = new Point(0, 0);

  public SketchPanel() {

  public void keyPressed(KeyEvent evt) {
    int keyCode = evt.getKeyCode();
    int d;
    if (evt.isShiftDown())
      d = 5;
      d = 1;
    if (keyCode == KeyEvent.VK_LEFT)
      add(-d, 0);
    else if (keyCode == KeyEvent.VK_RIGHT)
      add(d, 0);
    else if (keyCode == KeyEvent.VK_UP)
      add(0, -d);
    else if (keyCode == KeyEvent.VK_DOWN)
      add(0, d);

  public void keyReleased(KeyEvent evt) {

  public void keyTyped(KeyEvent evt) {

  public boolean isFocusTraversable() {
    return true;

  public void add(int dx, int dy) {
    endPoint.x += dx;
    endPoint.y += dy;
    Graphics g = getGraphics();
    g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
    startPoint.x = endPoint.x;
    startPoint.y = endPoint.y;

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(300, 200);
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {

    Container contentPane = frame.getContentPane();
    contentPane.add(new SketchPanel());;

Related examples in the same category

1.KeyListener, ActionListener Demo 1KeyListener, ActionListener Demo 1
2.KeyListener, ActionListener Demo 2KeyListener, ActionListener Demo 2
3.Responding to KeystrokesResponding to Keystrokes
4.Key Event DemoKey Event Demo
5.Set java.awt.Container.getFocusTraversalKeys(int id)
7.Activating a Keystroke When Any Component in the Window Has Focus
8.InputMap javax.swing.JComponent.getInputMap(int condition)
9.Activating a Keystroke When Any Child Component Has Focus
10.Listening to All Key Events Before Delivery to Focused Component
11.List keystrokes in the WHEN_ANCESTOR_OF_FOCUSED_COMPONENT input map of the component
12.List keystrokes in the WHEN_IN_FOCUSED_WINDOW input map of the component
13.Converting a KeyStroke to a String
14.Creating a KeyStroke and Binding It to an Action
15.void InputMap.put(KeyStroke keyStroke, Object actionMapKey)
16.Map actions with keystrokes
17.Handling Key Presses
18.Get key pressed as a key character (which is a Unicode character)
19.Get key pressed as a key code
20.Get Key Text
21.KeyStroke to String
22.Construct a new key description from a given universal string descriptionConstruct a new key description from a given universal string description
23.Reads for modifiers and creates integer with required mask