Search code examples
javaswingtextnetbeansjtextarea

Simple Program Help - How To Display Multiple Lines of Text in JTextAreas From An Array List?


I'm trying to write a program that stores 5 song titles in an ArrayList "cdNames", and outputs them in a text area, one title per line, 5 lines total.

Im using the .setText method and a for loop to try to pull the 5 elements from the ArrayList to display the 5 song titles, without having to explicitly write each title out.

What follows is the portion of my code that deals with the JTextArea:

private void btnDisplayMouseClicked(java.awt.event.MouseEvent evt) {
for (int i = 0; i<cdNames.size();i++){
txtOutputBox.setText(cdNames.get(i));

The problem lies in that the only thing displayed in the text area is the last element in the array list.

Index # 4 i.e. The Rolling Stones - Gimme Shelter.

I believe the setText method is overwriting the previous elements and stopping at the last, instead of printing out each title on a new line.

I think my troubles lie in my insufficient knowledge of how text areas display text.

I'm new to java, so please try to answer my question simply if possible.


Solution

  • You have to use either append() or insert() see JTextArea

    example (if your ArrayList has Strings)

    for (String cdName: cdNames) {
        txtOutputBox.append(cdName);
    }