Search code examples
javaarraysswingfilejtextarea

Output strings of an array into a JTextArea in java


Hi I have made a program that reads a text file containing words and adds it to an array. I now need the words to display in the JTextArea I have created but Im not sure how to. The text file contains one word per line, thats how I want the JTextArea to also display them.

Here is the code so far. The JTextArea I have is called textArea (its created in another method)

    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);
}

Solution

  • Create a JTextArea object.

    As, @Andrew suggested the correct function is JTextArea.append(String)

    JTextArea textArea = new JTextArea();
    
    for(String W: Words)
      textArea.append(W);
    

    JTextArea tutorial Java Swing