java中实现对按键的监听事件,按下按键有所显示

import java.awt.*;
import java.awt.event.*;

public class TestKeyEvent {
	public static void main (String args[]) {
		new MyFrame("KeyEvent test").LaunchMyFrame();
	}
}

class MyFrame extends Frame {
	MyFrame(String s) {                            //构造方法
		super(s);
	}
	
	public void LaunchMyFrame() {                 //定义一个运行窗体方法
		setLayout(null);                            //设置默认布局
		setSize(300,333);                           //设置窗体大小
		this.setBackground(new Color(211,222,233)); //设置窗体背景色
		setVisible(true);                           //设置窗体可见
		this.addKeyListener(new Monitor());         //Monitor要实现KeyListener接口(键盘监听)
	}
	
	class Monitor extends KeyAdapter {            //内部类,实现KeyListener的子类KeyAdapter
		public void keyPressed (KeyEvent e) {       //重写要实现的按下按键的方法
			int key = e.getKeyCode();                 //获取按下按键的虚拟码(int类型)
			if (key == KeyEvent.VK_UP) {              //与按键的虚拟码进行比较,是按下哪个按键
				System.out.println("up");               //向上箭头
			}
			else if (key == KeyEvent.VK_DOWN) {       //向下箭头   
				System.out.println("down");
			}
			else if (key == KeyEvent.VK_LEFT) {
				System.out.println("left");
			}
			else if (key == KeyEvent.VK_RIGHT) {
				System.out.println("right");
			}
			else {System.out.println("invalid input");}
		}
	}
}

你可能感兴趣的:(JAVA编程-GUI,java,GUI,按键监听,KeyEvent)