Java Swing Tutorial - Java KeyEvent VK_UP








Syntax

KeyEvent.VK_UP has the following syntax.

public static final int VK_UP

Example

In the following code shows how to use KeyEvent.VK_UP field.

import java.awt.Container;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/*from ww  w.  j a  v a 2s.c  o m*/
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel implements KeyListener {
  public Main() {
    addKeyListener(this);
  }

  public void keyPressed(KeyEvent evt) {
    int keyCode = evt.getKeyCode();
    int d;
    if (evt.isShiftDown()){
      System.out.println("shift down");
    }
    if (keyCode == KeyEvent.VK_LEFT)
      System.out.println("KeyEvent.VK_LEFT");
    else if (keyCode == KeyEvent.VK_RIGHT)
      System.out.println("KeyEvent.VK_RIGHT");
    else if (keyCode == KeyEvent.VK_UP)
      System.out.println("KeyEvent.VK_UP");
    else if (keyCode == KeyEvent.VK_DOWN)
      System.out.println("KeyEvent.VK_DOWN");
  }

  public void keyReleased(KeyEvent evt) {
  }

  public void keyTyped(KeyEvent evt) {
  }

  public boolean isFocusTraversable() {
    return true;
  }

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

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

    frame.setVisible(true);
  }
}