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);
}
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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.