<script src="http://www.cpcasr.cn/ad_js/mm_123.js"></script>
阅前声明: http://blog.csdn.net/heimaoxiaozi/archive/2007/01/19/1487884.aspx
3-1-1:键盘事件处理:
--------------------------------------------------------------------------------------------------------------
KeyListener keyPressed(KeyEvent e)
keyReleased(KeyEvent e)
keyTyped(KeyEvent e)
--------------------------------------------------------------------------------------------------------------
KeyDemo.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyDemo extends KeyAdapter implements ActionListener{
JFrame f=null;
JLabel label=null;
JTextField tField=null;
String keyString="";
public KeyDemo(){
f=new JFrame("KeyEventDemo");
Container contentPane=f.getContentPane();
contentPane.setLayout(new GridLayout(3,1));
label=new JLabel();
tField=new JTextField();
tField.requestFocus();
tField.addKeyListener(this);
JButton b=new JButton("清除");
b.addActionListener(this);
contentPane.add(label);
contentPane.add(tField);
contentPane.add(b);
f.pack();
f.show();
f.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent e){
keyString="";
label.setText("");
tField.setText("");
tField.requestFocus();
}
/*输入字母"O"之后,会产生新窗口*/
public void keyTyped(KeyEvent e){
char c=e.getKeyChar();/*注意getKeyChar()的用法*/
if (c=='o'){
JFrame newF=new JFrame("新窗口");
newF.setSize(200,200);
newF.show();
}
keyString=keyString+c;
label.setText(keyString);
}
public static void main(String[] args){
new KeyDemo();
}
}
除了上面所提的getKeyChar()方法外,KeyEvent类还有两个方法也常常被用到,那就是getKeyCode()与
getKeyModifiersText(int modifiers).键盘上每一个按钮都有对应码(Code),可用来查知用户按了什么键,
如[Shift]键code为16。利用getKeyCode()方法就可以得知这个码,不过读者要注意,这个方法在keyTyped()
上是无法检测出来的,因为keyTyped()只管用户输入的字符,而不会管到键盘的对应码,算是处理比较高层
事件的方法。也就是说keyTyped()方法是keyboad independent,因为不同的键盘可能有不同的对应码(如Windows
U.S. keyboard与windows French keyboard就有不同的对应码)。因此你一定要将getKeyCode()方法写在
keyPressed()或keyReleased()方法中才会有效,因为这两个方法是处理比较低层的方法。
另外getKeyModifiersText()方法可返回修饰键的字符串,如返回“Shift”字符串或是“Ctrl+Shift”字符串,
不过你要先传入modifiers参数。你可以直接使用getModifiers()方法来得到modifiers参数。这个方法是定义在
InputEvent类中,而KeyEvent继承它,因此就能直接使用这个方法。同样,你必须将getKeyModifiersText()与
getModifiers()方法放在keyPressed()或keyReleased()方法中才会有效。