2015-08-08 57 views
-5

嗨,我做了一個包含jtextfield和幾個jbuttons的程序。我想按jbutton,以便將jtextfields保存到計算機中。任何幫助都是有用的。試圖發送數據到文本文件

+2

你爲什麼不看一個關於將數據保存到文件的教程?他們很豐富 – SamTebbs33

+0

你到目前爲止已經嘗試過什麼? – Seb

+0

那麼你的問題是什麼?你知道如何做文件I/O嗎?你知道如何在單擊按鈕時執行代碼嗎?你知道如何從文本字段中獲取文本嗎?當你問一個問題時具體。我們無法猜測是什麼導致了你的問題。從「Java教程」開始。有I/O教程和使用Swing應該回答你所有的問題。 – camickr

回答

0

我認爲這將幫助你..

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {           

    if (jTxt_text.getText().isEmpty()) { 
     JOptionPane.showMessageDialog(rootPane, "Field is empty. Fill the filed and try again."); 
    } else { 
     //get the text from the jTextField and save it into a varibale. 
     String inputText = jTxt_text.getText(); 
     //Where to save the file. 
     String savePath = "C:/test/sample.txt"; 

     //Creating a file object, file is an abstract representation of file and directory pathnames. 
     File tempFile = new File(savePath); 

     //Check wther the file is available or not. 
     if (!tempFile.exists()) { 
      try { 
       //Creates the file if it's not exsising. 
       tempFile.createNewFile(); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 

     try { 
      //writing process.. 
      FileWriter tempWriter = new FileWriter(tempFile.getAbsoluteFile()); 
      BufferedWriter tempBufferWriter = new BufferedWriter(tempWriter); 
      tempBufferWriter.write(inputText); 
      tempBufferWriter.close(); 

      JOptionPane.showMessageDialog(rootPane, "Text file with the written text is successfully saved."); 
      jTxt_text.setText(null); 

     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 
} 

仍然有一個小問題,此代碼tempBufferWriter.write(inputText)返回void所以..我不知道如何檢查wther從代碼本身成功地完成了過程..

+0

我會給它一個機會 –

+0

我有很多文本字段在同一時間寫15 15確切地說,他們並不都必須是字段。那麼使用這段代碼應該能夠寫出所有這些代碼? –

+0

這是一個基本的代碼,你可以獲得一個'jTextField'的值並將其寫入一個文本文件中......可能有'jTextAreas','JComboBoxes','jRadioButtons',所以你必須做的只是獲取所有這些組件的值,然後保存到變量中並構建一個單獨的字符串。並將其作爲寫入方法的參數傳遞。 – ZeroKool