【问题标题】:Use arrayList to display in JTextArea使用arrayList在JTextArea中显示
【发布时间】:2013-11-26 13:03:41
【问题描述】:

我希望能够在 JTextArea 中显示 arrayList 中的所有项目。这是我的代码,但它不起作用。

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

【问题讨论】:

  • 如果是正确的,它将只显示一个文本区域,因为它只是用另一个文本区域覆盖一个文本区域,因为所有文本区域的大小和位置都是相同的,只需在其后设置 JTextArea 的位置已创建。

标签: java swing arraylist textarea containers


【解决方案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);
}

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

【讨论】:

    【解决方案2】:

    有几种方法可以实现这一点。首先,您的示例代码为每个 Shape 创建一个新的 JTextArea,但它只会将最后一个添加到 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- 您可能希望将文本区域包裹在 JScrollPane 中,以便它可以溢出

    【讨论】:

      猜你喜欢
      • 2015-07-25
      • 2015-08-19
      • 2013-07-27
      • 2013-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-17
      • 2013-05-22
      相关资源
      最近更新 更多