对窗口添加侦听器,当窗口为活动时,连续键入‘o','v','e','r'四个字母时,窗口退出。。求更好的实现代码?
以下是我自己写的代码,望指点:
- import java.awt.*;
- import java.awt.event.*;
- class KeyEventTest
- {
- public static void main(String [] args)
- {
- new KeyEventFrame();
- }
- }
- class KeyEventFrame
- {
- Frame f=null;
- public static final String EXIT_FLAG="over";
- private int ExitFlagLength= EXIT_FLAG.length();
- int count=0;
- KeyEventFrame()
- {
- init();
- }
- //对KeyEventFrame窗口进行初始化
- private void init()
- {
- f=new Frame("键盘事件测试:键入\""+EXIT_FLAG+"\"退出窗口");
- f.setBounds(300,200,600,300);
- addListeners();
- f.setVisible(true);
- }
-
- private void addListeners()
- {
- f.addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- System.out.println("点击‘X’-->退出窗口");
- System.exit(0);
- }
- });
- f.addKeyListener(new KeyAdapter()
- {
- public void keyTyped(KeyEvent e)
- {
- char c=e.getKeyChar();
- if (EXIT_FLAG.charAt(count)==c)
- {
- count++;
- if (count==ExitFlagLength)
- System.exit(0);
- }else{
- count=0;
- }
- System.out.println(c+"---->"+count);
-
- }
-
- });
- }
- }
复制代码 |