KeyListener也有两个事件方法:
1. KeyPressed 和 KeyReleased
KeyPressed:顾名思义,摁下键盘触发事件;
KeyReleased:松开摁键触发。
2.事件对象KeyEvent有三个属性比较有用:
character:得到按键对应的字符,类型为char,所以包括汉字等编码值。
keyCode: 得到按键码。如a在键盘的摁键码为97;
stateMask: 利用 & (位与)运算来判断是否某个键被摁下。多用来检测是否同时按下 Ctrl, Alt, Shift 键。
如:
package com.iteye.niewj.swt.chapter1; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class KeyEventShow { /** * @author niewj * @since 2012-6-1 */ public static void main(String[] args) { Display display = new Display(); //1.一个窗口 final Shell shell = new Shell(display); shell.setText("键盘监听器"); shell.setBounds(60, 40, 300, 400); //2.一个按钮 Label label = new Label(shell, SWT.PUSH); label.setText("输入框"); label.setBounds(10, 50,100, 25); final Text text = new Text(shell, SWT.BORDER|SWT.PASSWORD); text.setBounds(120, 50, 150, 25); final Text result = new Text(shell, SWT.BORDER|SWT.MULTI|SWT.WRAP); result.setBounds(120, 80, 150, 125); /* 键盘监听器 */ text.addKeyListener(new KeyListener() { @Override public void keyReleased(KeyEvent e) { result.setText(text.getText()); } @Override public void keyPressed(KeyEvent e) { System.out.println("摁下键盘:"+e.character+" = "+e.keyCode); boolean flag1 = (e.stateMask & SWT.CTRL)!=0; //同时按下Ctrl+一个其他键就不为0 boolean flag2 = (e.stateMask & SWT.ALT)!=0; //同时按下Alt+一个其他键就不为0 System.err.println(flag1+";"+flag2); if(flag1 && flag2){ System.err.println("您同时按下了Ctrl+Alt+其他键"); } } }); //4.设置显示 shell.layout(); shell.open(); while(!shell.isDisposed()){ if(!display.readAndDispatch()){ display.sleep(); } } display.dispose(); } }