2012-09-13 63 views
0

我寫了一個代碼「將文本內容寫入文本文件」。它沒有錯誤,但它不會在文本文件中寫入任何內容!任何人都可以幫助我並告訴我的錯誤嗎?或編輯代碼並重新輸入整個代碼。不寫文本文件從文本輸入

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {           
    // TODO add your handling code here: 
    jButton1.addActionListener(new ActionListener(){ 
     public void actionPerformed(final ActionEvent e){ 
      handleActionPerformed(e); 
     } 
    }); 
}           

/** 
* @param args the command line arguments 
*/ 

public static void main(String args[]) { 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      new NewJFrame().setVisible(true); 
     } 
    }); 
} 

//do you really need to pass ActionEvent in this case? 
protected void handleActionPerformed(ActionEvent e) { 
    BufferedWriter writer = null; 
    try 
    { 
     String text = jTextField1.getText(); //get the text from the text field 
     writer = new BufferedWriter(new FileWriter("D:\\Definition.txt")); 
     writer.write(text); //write it in the file 
     writer.flush(); //flush the write-buffer 
    } 
    catch (IOException ioe) 
    { 
     ioe.printStackTrace(); 
    } 
    finally { //always close the stream in finally block 
     try { 
      if(writer != null) 
       writer.close(); 
     } 
     catch(IOException b) { 
      b.printStackTrace(); 
     } 
    } 
} 
+0

添加調試語句中'handleActionPerformed'這樣你就可以知道它實際上是獲取調用。 – DanielGibbs

回答

3

handleActionPerformed(...)什麼都不做。 這應該工作。我相信

jButton1.addActionListener(new ActionListener() { 
    public void actionPerformed(final ActionEvent e) { 
     handleActionPerformed(e); 
    }          
} 

//do you really need to pass ActionEvent in this case? 
protected void handleActionPerformed(ActionEvent e) { 
BufferedWriter writer = null; 
try 
{ 
    String text = jTextField1.getText(); //get the text from the text field 
    writer = new BufferedWriter(new FileWriter("C:\\Definition.txt")); 
    writer.write(text); //write it in the file 
    writer.flush(); //flush the write-buffer 
} 
catch (IOException ioe) 
{ 
    ioe.printStackTrace(); 
} 
finally { //always close the stream in finally block 
    try { 
    if(writer != null) 
     writer.close(); 
    } catch(IOException e) { 
    e.printStackTrace(); 
    } 
} 
} 
+0

你好。我使用了你編寫的編輯過的代碼(現在我用新代碼編輯了這個主題,你可以將它看作是最新版本),但仍然沒有任何內容會出現在definition.txt文件中......你可以看看頁面上方的帖子看看是不是又錯了?謝謝 – SunnY

+0

@SunnY當您創建GUI並設置所有其他揮杆組件時,應該完成'jbutton1.addActionListener ...'代碼。不像您在問題中編輯的代碼中所做的那樣使用自己的方法。 – DanielGibbs

+0

@Sunny這個小小的演示http://pastebin.com/FQH5PuFZ在我的機器上工作 – nullpotent