【问题标题】:Why does this attempt to output an arrayList object to a JtextArea not work?为什么这种将 arrayList 对象输出到 JtextArea 的尝试不起作用?
【发布时间】:2010-10-26 21:18:45
【问题描述】:
ArrayList list_of_employees = new ArrayList();
@Action
public void reportAllEmployeesClicked(java.awt.event.ActionEvent evt)
{
    this.outputText.setText("");
    int i=0;
    //JOptionPane.showMessageDialog(null,"test Employee list print");
    ListIterator list_ir = list_of_employees.listIterator(); //list_of_employees is of    
       //obj type ArrayList
    while(list_ir.hasNext())
        {
            String o = new String();
            o = (String) list_ir.next();
            this.outputText.setText(""+o); // this does not work, why? nothing happens   
                //no errors and no output
            i++;
            JOptionPane.showMessageDialog(null,o); // this works
        }
}  

outputText 是嵌套在滚动窗格内的 JTextArea 类型。 当我使用普通字符串变量设置文本时,输出会按原样显示。 当循环运行时,我能够通过 JOptionPane 获得输出。 存储在列表中的所有对象都是 String 对象。 如果我需要提供更多信息以帮助获得更准确的答案,请告诉我。

谢谢 -会-

【问题讨论】:

    标签: java object arraylist jtextarea


    【解决方案1】:
    this.outputText.setText(""+o); 
    

    您不应该使用 setText(),因为您将替换现有文本。因此只会出现最后一个字符串。

    你应该使用:

    this.outputText.append(""+o); 
    

    【讨论】:

    • 我错过了 jtextarea 的 java api 中的那个花絮。非常感谢。
    【解决方案2】:
    // use generics
    List<String> list_of_employees = new ArrayList<String>();
    
    // use StringBuilder to concatenate Strings
    StringBuilder builder = new StringBuilder();
    
    // use advanced for loop to iterate a List
    for (String employee : list_of_employees) {
          builder.append(employee).append(" ");  // add some space 
    }
    
    // after they are all together, write them out to JTextArea
    this.outputText.setText(builder.toString());
    

    【讨论】:

      【解决方案3】:

      您也可以使用 StringBuffer 类。您可以将字符串附加在一起,最后使用 .toString() 方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-03
        • 2019-01-27
        • 2013-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多