键盘事件

来自CloudWiki
跳转至: 导航搜索

键盘事件

在按下或释放键盘上的一个键时,将生成键盘事件。 KeyEvent事件类的主要方法有:

puhlic char getKeyChar():用来返回一个被输入的字符
public String  getKeyText():用来返回被按键的键码
public String  getKeyModifiersText():用来返回修饰键的字符串

public int getKeyCode()返回与此事件中的键相关联的整数 keyCode。KeyEvent 类包含用来表示按下或点击的键的常量键码。keyCode 是每个按键的编码,JDK帮助中可以查到每个按键对应的键码常量,如 A 对应于 VK_A。

键盘事件监听器

处理键盘事件的程序要实现在java.awt.event包中定义的接口KeyListener,在这个接口中定义了未实现的键盘事件处理方法。在这个接口中定义了三个方法:当一个键被按下和释放时,kevPressed()方法和keyReleased()方法将被调用;当一个字符被输入时,keyTyped()方法将被调用。如果程序需要处理特殊的键,如方向键,需要通过调用keyPressed( ) 方法来处理。

键盘事件处理方法为:

public void KeyPressed(KeyEvent e)处理按下键。
public void KeyReleased(KeyEvent e)处理松开键。
public void KeyTyped(KeyEvent e)处理敲击键盘。


案例精选:改变窗口颜色(二)

Java8-11.png


分步步骤

构建窗体布局

package main;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.*;

public class BackGroundColor2 extends JFrame {
	private JButton button;	
	final JPanel buttonPanel;
	
	public BackGroundColor2(){
		super("改变颜色");
		button = new JButton("改变颜色");	
		
		buttonPanel = new JPanel();
		buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
		buttonPanel.add(button);		
		add(buttonPanel);
		
		setSize(300,200);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}
	public static void main(String[] args) {
		 BackGroundColor2 bg = new BackGroundColor2();
	}
	
	
}

分析窗体事件

KeyEvent

编写事件监听器

private class ColorKey implements  KeyListener{
		
		public ColorKey(){}
		@Override
		public void keyPressed(KeyEvent e){
	        int t = e.getKeyCode();
	        if(t==KeyEvent.VK_R){
	        	buttonPanel.setBackground(Color.RED);
	        }
	        if(t==KeyEvent.VK_G){
	        	buttonPanel.setBackground(Color.GREEN);
	        }
	        if(t==KeyEvent.VK_B){
	        	buttonPanel.setBackground(Color.BLUE);
	        }
	    }
		 public void keyTyped(KeyEvent e){}
		 public void keyReleased(KeyEvent e){}	
	}
	
}

绑定事件监听器

button.addKeyListener(new ColorKey());