2017-09-27 126 views
0

。我的嘗試&是否捕獲到事件處理程序方法中的正確位置,還是應該將它的一部分放在構造函數中?如果我在JTextArea中輸入文本並單擊「保存」按鈕,則JTextArea文本應該寫入/保存到.txt文件中,從而將JTextArea保存爲帶有按鈕的.txt文件

這是我的代碼:提前

package exercises; 

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.io.PrintWriter; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JTextArea; 

public class SimpleNotePadApp extends JFrame implements ActionListener { 

JButton button1 = new JButton("Open"); 
JButton button2 = new JButton("Save"); 

public SimpleNotePadApp(String title) { 
    super(title);        
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    setSize(300, 350);       
    setLayout(null); 


    JTextArea newItemArea = new JTextArea(); 
    newItemArea.setLocation(3, 3); 
    newItemArea.setSize(297, 282); 
    getContentPane().add(newItemArea); 

    button1.setLocation(30,290); 
    button1.setSize(120, 25); 
    getContentPane().add(button1); 

    button2.setLocation(150,290); 
    button2.setSize(120, 25); 
    getContentPane().add(button2); 

} 

public static void main(String[] args) { 
    SimpleNotePadApp frame; 

    frame = new SimpleNotePadApp("Text File GUI");  
    frame.setVisible(true);        
} 

public void actionPerformed(ActionEvent e) { 

    if(e.getSource() == button1) 
    { 
     try { 
      PrintWriter out = new PrintWriter(new FileWriter("TestFile.txt")); 
      newItemArea.getText(); 
      newItemArea.write(out); 
      out.println(newItemArea); 
      out.flush(); 
      out.close(); 

     } catch (IOException e1) { 
      System.err.println("Error occurred"); 
      e1.printStackTrace(); 
     } 
    } 
} 
} 

感謝

+3

'是我試着抓在正確的地方......' - 爲什麼會在構造函數中?你是否從構造函數執行你的代碼?另外,使用JTextArea.write(...)方法將數據保存到文件中。 – camickr

+0

Java GUI必須在不同的語言環境中使用不同的PLAF來處理不同的操作系統,屏幕大小,屏幕分辨率等。因此,它們不利於像素的完美佈局。請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[white space]的佈局填充和邊框(http://stackoverflow.com/a/17874718/ 418556)。 –

回答

0

try ... catch是在正確的位置,但內容應該僅僅是:

 PrintWriter out = new PrintWriter(new FileWriter("TestFile.txt")); 
     newItemArea.write(out); 
     out.close(); 

考慮使用try-與資源,並且.close()變得不必要:

try (PrintWriter out = new PrintWriter(new FileWriter("TestFile.txt")) { 
     newItemArea.write(out); 
    } catch (IOException e1) { 
     System.err.println("Error occurred"); 
     e1.printStackTrace(); 
    } 

另外,你需要在施工期間給ActionListener連接到JButton

button2.addActionListener(this); 

thisSimpleNotePadApp實例,它實現ActionListener

最後,你會想:

if(e.getSource() == button2) 

...因爲button2是你的「保存」按鈕(不是button1

+0

感謝您的幫助!但是,由於某些原因,它仍然沒有保存到文本文件中。這絕對是通過「嘗試」部分,因爲我已經通過打印到控制檯上進行了測試...... – Caiz

+0

您確定它沒有寫入文本文件嗎?爲了進行調試,我建議對問題中的代碼進行一些更改。例如。改變'PrintWriter out = new PrintWriter(new FileWriter(「TestFile.txt」));'to'File f = new File(「TestFile.txt」); PrintWriter out = new PrintWriter(new FileWriter(f));'然後稍後(保存之後),執行'Desktop.getDesktop()。open(f);' –