2011-10-28 42 views
1

我是java新手。使用新值刷新JTextArea

我有一個大學的項目,我必須通過2 JTextField框和1 JButton(保存)將條目顯示在JTextArea中的條目到txt文件中。我能夠成功地在txt文件中進行輸入。但是如何在運行時刷新JTextArea以顯示我最近創建的新條目?

感謝幫助: 下面是我的代碼:

try { 
      //use buffering, reading one line at a time 
      //FileReader always assumes default encoding is OK! 
      BufferedReader input = new BufferedReader(new FileReader("RokFile.txt")); 
      try { 
       String line = null; //not declared within while loop 

       while ((line = input.readLine()) != null){ 
        jTextArea1.append(line+"\n"); 
       } 
      } 
      finally { 
       input.close(); 

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

讓我知道,如果它的正確嗎? 謝謝

+0

請將[tag:homework]標籤添加到作業問題中。 –

+0

它工作嗎?如果它有效,那麼我會說這是正確的。 –

+0

它不起作用,只要我在JTextfields中創建,它就不會顯示新條目。 – Rockwire

回答

1

JTextArea.append應該足夠。此方法是線程安全的,並會自動更新文本區域的內容。

此答案假定您已經配置了EventListeners。

+0

嗨,如果上面的代碼(問題更新)是正確的,你能不能讓我知道? – Rockwire

+0

JTextArea.append實際上並不是線程安全的:http://bugs.java.com/view_bug.do?bug_id=4765383 –

1

您可以使用兩種方法,

  1. 如果你想,只要你在jTextField(相當實現的)寫顯示的內容,你能做到這樣,在FocusLost事件jTextField,看到這樣的信息jTextArea.setText(jTextField.getText()) 請注意,這是相當接近你想要什麼。(還,不完美的代碼)

  2. 如果你想,當你點擊save,上面的代碼中顯示的內容,jTextArea.setText(jTextField.getText())可以給予該save按鈕的事件處理程序。