2011-03-15 45 views
1

我在JFrame和JButton上有一個JTextArea。如何從JTextArea中獲取文本?

當用戶在JTextArea textArea上鍵入字符並按下按鈕時,我希望信息保存在textFile中。

JTextArea textArea = new JTextArea(2, 20); 
    textArea.setLineWrap (true); 

    thehandler4 handler4 = new thehandler4(); // next button 
    button4.addActionListener(handler4); 


    private class thehandler4 implements ActionListener{ //next button 
     public void actionPerformed(ActionEvent event){ 


     PrintWriter log = null; 
     try { 

       FileWriter logg =new FileWriter("logsheet.txt",true); 
       log = new PrintWriter(logg); 

       log.println("Quick Notes: "+textArea); 
       log.close(); 
      } catch(Exception y) { y.printStackTrace(); } 

    }} 

但是,當我打開logsheet.txt,我沒有看到任何東西。其爲空。有沒有我需要的函數textArea.getText();我嘗試過,但我得到一個錯誤。

+0

你在做什麼時會出現錯誤:textArea.getText()? – 2011-03-15 23:50:11

+0

顯示java.lang.NullPointerException \t在AdjustmentForm $ thehandler4.actionPerformed(AdjustmentForm.java:150) – razshan 2011-03-15 23:53:56

回答

2

我猜你的問題是,你有你的文本區域定義爲一個類vararaible和局部變量。您的ActionListener正在訪問空變量的類變量。

//JTextArea textArea = new JTextArea(2, 20); // this is wrong, you don't want a local variable 
textArea = new JTextArea(2, 20); 

此外,使用textArea.write(...)方法是正確的方法。您不想使用getText()方法,因爲該方法可能會導致字符串中包含錯誤的換行符。

+0

感謝描述了同樣的錯誤,我只是注意到了。 – razshan 2011-03-16 00:09:05

0

你可以做,而不是執行以下操作:

JTextArea textArea = new JTextArea(2, 20); 
FileWriter logg =new FileWriter("logsheet.txt",true); 
textArea.write(logg); 

的write()方法允許你寫從文本區文本作家。

+0

它編譯罰款和執行,但我得到上述 – razshan 2011-03-16 00:02:04