键盘的触发事件

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Key extends JFrame  {
public Key(){
final JLabel label=new JLabel();//创建标签
getContentPane().add(label,BorderLayout.WEST);//添加到面板并放在西边
final JScrollPane scrollPane=new JScrollPane();//创建滚动条面板
getContentPane().add(scrollPane,BorderLayout.CENTER);
JTextArea textArea=new JTextArea();//创建文本域
textArea.addKeyListener(new KeyListener(){
	public void keyPressed(KeyEvent e){//按键被按下事触发
		String keyText=KeyEvent.getKeyText(e.getKeyCode());//获得标签
		if(e.isActionKey()){
			System.out.println("你按下的是动作键"+keyText+" ");
		}else{
			System.out.print("你按下的是非动作间"+keyText+" ");
			int keyCode=e.getKeyCode();
			switch(keyCode){
			case KeyEvent.VK_CONTROL:
				System.out.print(", Ctril键被按下");break;
			case KeyEvent.VK_ALT:
				System.out.print(", Alt键被按下");break;
			case KeyEvent.VK_SHIFT:
				System.out.print(",shift键被按下");break;
			}
			System.out.println();
		}
	}
	public void keyTyped(KeyEvent e){//发生击剑时间的触发
		System.out.println("此次输入的是"+e.getKeyChar()+" ");//获得输入的字符
		}
	public void keyReleased(KeyEvent e){
		String keyText=KeyEvent.getKeyText(e.getKeyCode());//被释放时触发
		System.out.println("你释放的是"+keyText+"键");
		System.out.println();
	}
});
textArea.setLineWrap(true);//换行
textArea.setRows(3);
textArea.setColumns(15);
scrollPane.setViewportView(textArea);//将文本域添加到滚动条面板
setSize(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
	public static void main(String[] args) {
		 new Key().setVisible(true);
	}

}

你可能感兴趣的:(键盘的触发事件)