fathertodumptious
fathertodumptious

Reputation: 53

Use arrayList to display in JTextArea

I want to be able to display all items in an arrayList in a JTextArea. This is the code I have but it does not work.

public void display()
{
    JPanel display = new JPanel();
    display.setVisible(true);
    JTextArea a;

    for (Shape ashape : alist)
    {
        System.out.println("");
        System.out.println(ashape.toString());
        a = new JTextArea(ashape.toString()); 
        display.add(a);
    }

    Container content = getContentPane(); 
    content.add(display);
}

Upvotes: 0

Views: 464

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347332

There are a couple of ways to achieve this. To start with, your example code is creating a new JTextArea for each Shape, but it is only ever adding the last to the UI.

Assuming you want to display all the information in a single text area, you could simply use JTextArea#append, for example

JTextArea a = new JTextArea();

for (Shape ashape : a list)
{
    System.out.println(ashape.toString());
    a.append(ashape.toString() + "\n")
}

Container content = getContentPane(); 
content.add(display);

Ps- you may want to wrap the text area within a JScrollPane so it can overflow

Upvotes: 1

Melquiades
Melquiades

Reputation: 8598

Move

JTextArea a;

inside for loop, like so:

for (Shape ashape : alist) {
        System.out.println("");
        System.out.println(ashape.toString());

        //initialise a here 
        JTextArea a = new JTextArea(ashape.toString()); 
        display.add(a);
    }

    Container content = getContentPane(); 
    content.add(display);
}

Also, what does it mean "it doesn't work" in your program?

Upvotes: 1

Related Questions