{相关信息}
键盘事件类(KeyEvent)是容器内的任意组件获得焦点时,组件发生键击事件,当按下释放或键入某一个键时,组件对象将产生该事件。使用键盘事件必须给组件添加一个KeyListener 接口的事件处理器,该接口包含以下 3 个方法:
void keyPressed(KeyEvent e):按下按键时发生。
void keyReleased(KeyEvent e):松开按键时发生。
void keyTyped(KeyEvent e):敲击键盘,发生在按键按下后,按键放开前。
{效果图}
{实现代码}
package sup.orange.learn; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /** * Created by re-x on 10/31/14. */ public class KeyEventDemo extends Frame implements KeyListener { TextArea textarea, textarea1; Button button; public KeyEventDemo () { super(); init(); } public static void main(String[] args) { new KeyEventDemo(); } public void init() { setLayout(new GridLayout(3, 1)); textarea = new TextArea(); textarea1 = new TextArea(); add(textarea); button = new Button("click me first, then click any other key"); add(button); button.addKeyListener(this); add(textarea1); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); dispose(); System.exit(0); } }); setSize(200, 300); setVisible(true); } public void keyPressed(KeyEvent e) { textarea.setText("key pressed"); } public void keyReleased(KeyEvent e) { textarea.setText("key released"); } public void keyTyped(KeyEvent e) { textarea1.setText(String.valueOf(e.getKeyChar())); } }