KeyEvent.VK_LEFT : KeyEvent « java.awt.event « Java by API






KeyEvent.VK_LEFT

 

import java.awt.Container;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

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

public class Main extends JPanel implements KeyListener {

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

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

  public Main() {
    addKeyListener(this);
  }

  public void keyPressed(KeyEvent evt) {
    int keyCode = evt.getKeyCode();
    int d;
    if (evt.isShiftDown())
      d = 5;
    else
      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);
    g.dispose();
    startPoint.x = endPoint.x;
    startPoint.y = endPoint.y;
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("Sketch");
    frame.setSize(300, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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

    frame.setVisible(true);
  }
}
   

   
  








Related examples in the same category

1.KeyEvent.KEY_LOCATION_LEFT
2.KeyEvent.KEY_LOCATION_NUMPAD
3.KeyEvent.KEY_LOCATION_RIGHT
4.KeyEvent.KEY_LOCATION_STANDARD
5.KeyEvent.KEY_TYPED
6.KeyEvent.VK_B
7.KeyEvent.VK_DOWN
8.KeyEvent.VK_N
9.KeyEvent.VK_RIGHT
10.KeyEvent.VK_U
11.KeyEvent.VK_UP
12.KeyEvent: getKeyChar()
13.KeyEvent: getKeyCode()
14.KeyEvent: getKeyLocation()
15.KeyEvent: getKeyText(int keyCode)
16.KeyEvent: isActionKey()