0

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

2 回答 2

1

有几种方法可以实现这一目标。首先,您的示例代码JTextArea为 each创建一个新的Shape,但它只是将最后一个添加到 UI。

假设您想在单个文本区域中显示所有信息,您可以简单地使用JTextArea#append,例如

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-您可能希望将文本区域包装在 a 中JScrollPane,以便它可以溢出

于 2013-11-13T19:10:53.023 回答
1

移动

JTextArea a;

在for循环里面,像这样:

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

另外,在您的程序中“它不起作用”是什么意思?

于 2013-11-13T19:10:29.860 回答