用java如何将一个键盘发生的事件记录到记事本里呀?我代码如下:但不知出错在哪里啦?
import   java.io.*;
import   java.awt.*;
import   java.awt.event.*;
import   javax.swing.*;
public class KeyEventTest   extends   JFrame {
   private    String  output;
   public  KeyEventTest(){
   super("显示键盘事件演示程序");
   addKeyListener(new   KeyEventHandler());
  
   setSize(200,200);
   show();
   } 
   public  static  void  main(String  args[]){
   KeyEventTest  app=new   KeyEventTest();
   }
   class   KeyEventHandler   implements  KeyListener{
   private   char  output;
   private  String  output1;
   public  void  keyPressed(KeyEvent  e){
   output1="键盘按下:"+e.getKeyText(e.getKeyCode());
   }
   public  void  keyTyped(KeyEvent  e){
   output=e.getKeyChar();
   }
   public   void  keyReleased(KeyEvent  e){}
   private   void  show()  throws  IOException {
  File  file1=new   File("e:\\keyrecord.txt");
  try{
  FileOutputStream  fout=new  FileOutputStream(file1);
  fout.write(output);   
          fout.close();
    }
  catch (FileNotFoundException  e)
  {  System.out.println(e);} 
  catch(IOException   e)
  {  System.out.println(e);}
  
        }  
}
}

解决方案 »

  1.   

    KeyEventTest 中的output和KeyEventHandler 中的output分别指向不同对象,在需要输出时自然没有内容输出了
      

  2.   

    package keyboard;import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;import javax.swing.JFrame;public class KeyEventTest extends JFrame {
    /**
     * 
     */
    private static final long serialVersionUID = 1L; private static StringBuffer buffer = new StringBuffer(); public static void main(String[] args) {
    new KeyEventTest().show();
    } private KeyEventTest() {
    this.setSize(200, 200);
    addKeyListener(new KeyListener() { public void keyPressed(KeyEvent arg0) {
    // record the key pressed
    buffer.append("Key down : " + arg0.getKeyChar());
    } public void keyReleased(KeyEvent arg0) { } public void keyTyped(KeyEvent arg0) { }
    });
    addWindowListener(new WindowListener() { public void windowActivated(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowClosing(WindowEvent arg0) {
    // save before quit
    System.out.println("quit!");
    try {
    File file = new File("c:\\output.txt");
    if (file.exists())
    file.delete();
    file.createNewFile();
    BufferedOutputStream bos = new BufferedOutputStream(
    new FileOutputStream(file));
    bos.write(buffer.toString().getBytes());
    bos.flush();
    bos.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    System.exit(0);
    } public void windowDeactivated(WindowEvent arg0) {
    } public void windowDeiconified(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowOpened(WindowEvent arg0) {
    }
    });
    }
    }