【问题标题】:how to add ArrayList<String> to table?如何将 ArrayList<String> 添加到表中?
【发布时间】:2015-01-28 19:27:25
【问题描述】:

从下面的数组列表中,我需要删除逗号并将每个元素添加到 JTable 中的一个单元格中。例如,My JTable - 将有 12 列,第 1 行应填充 0 0 0 ....

请求您帮助我从列表中删除逗号并将元素添加到 JTable 中的单元格。

//代码

ArrayList 列表 = 新的 ArrayList();

list.add("0 , 0 , 0 , 4 , 2 , 0 , 2 , 0 , 1 , 0 , 0 , 0");

list.add("1 , 0 , 0 , 4 , 2 , 0 , 3 , 0 , 1 , 0 , 0 , 1");

list.add("2 , 0 , 0 , 4 , 1 , 0 , 2 , 0 , 1 , 0 , 0 , 0");

【问题讨论】:

    标签: java swing arraylist jtable defaulttablemodel


    【解决方案1】:
    ArrayList list = new ArrayList();
    
    list.add("0 , 0 , 0 , 4 , 2 , 0 , 2 , 0 , 1 , 0 , 0 , 0");
    
    list.add("1 , 0 , 0 , 4 , 2 , 0 , 3 , 0 , 1 , 0 , 0 , 1");
    
    list.add("2 , 0 , 0 , 4 , 1 , 0 , 2 , 0 , 1 , 0 , 0 , 0");
    
    //now go through the ArrayList and split each entry by ',' and add to a 2D array, JTable
    
    int[][] JTable = new int[list.size()][];
    for (int row = 0; row < list.size(); row++) {
        //get an item from the ArrayList
        String rowString = list.get(row);
        //remove all the whitespaces from the string
        rowString = rowString.replaceAll("\\s+","");
        //split the string using "," as a delimiter
        String[] items = rowString.split(",");
        JTable[row] = new int[items.length];
        for (int col = 0; col < items.length; col++) {
            JTable[row][col] = Integer.parseInt(items[col]);
        }
    }
    

    【讨论】:

    • 谢谢大卫!我正在使用默认的 Table 模型向 JTable 添加行......所以,让我试试吧!
    • rowString = rowString.replaceAll("\\s+","")
    • 我可以分隔逗号并显示信息!感谢您的帮助!
    • 永远不要使用默认的表模型。创建您自己的从 AbstractTableModel 派生的
    【解决方案2】:

    以下代码可以正常工作!发布代码以帮助其他程序员....

    //新逻辑 for (int row = 0; row

        {
    
            String rowString = recommendedTestSet.get(row);
    
            rowString = rowString.replaceAll("\\s+","");
    
            String[] items = rowString.split(",");
    
            rtsTable.addRow(items);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-22
      • 2011-12-24
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      相关资源
      最近更新 更多