2012-01-28 280 views
2

嗨我已經做了一個程序,讀取包含單詞的文本文件並將其添加到數組中。我現在需要在我創建的JTextArea中顯示的單詞,但我不知道如何。該文本文件每行包含一個單詞,這就是我想讓JTextArea也顯示它們的方式。將數組輸出到java中的JTextArea

這是目前爲止的代碼。我有JTextArea中被稱爲textarea的(它在另一種方法創建)

public static void file() { 

    List<String> wordList = new ArrayList<String>(); 

    BufferedReader br = null; 
    try { 

     br = new BufferedReader(new FileReader("data/WordFile.txt")); 
     String word; 

     while ((word = br.readLine()) != null) { 
      wordList.add(word); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      br.close(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 
    String[] words = new String[wordList.size()]; 
    wordList.toArray(words); 
} 
+0

你所描述的問題,以及如何你不能做到這一點,但到目前爲止還沒有問了一個問題(讓單獨一個具體的,可回答的問題)。你有問題嗎? – 2012-01-28 17:25:37

+0

*「..文件每行包含一個單詞,這就是我想怎樣也顯示它們。」*聽起來像一個項目列表。在這種情況下,通過'JTextArea'查找'JList'。 – 2012-01-28 17:28:00

+0

哇 - 我需要在JTextArea中顯示數組內容的幫助。另外我需要使用JTextArea – jj007 2012-01-28 17:28:15

回答

5

創建一個JTextArea對象。

爲,@Andrew建議正確的功能是JTextArea.append(String)

JTextArea textArea = new JTextArea(); 

for(String W: Words) 
    textArea.append(W); 

JTextArea tutorial Java Swing

+0

我試過了,它只顯示數組中的最後一個單詞。我希望它能夠顯示整個數組 – jj007 2012-01-28 17:27:15

+0

當我學習這些時,您可能不想詳細說明「對象」,但我不知道對象如何能夠幫助別人如何實現它。 – Russell 2012-01-28 17:27:23

+0

@Russell:這就是爲什麼我添加了正式的教程鏈接。 – RanRag 2012-01-28 17:28:39

2

this教程看看,看看如何使用文字區域。基本上,你想要做的就是迭代數組並通過Event Dispatcher Thread(負責GUI的線程)打印它的內容。這通常通過使用SwingUtils.invokeLater()