【问题标题】:getting data from jtable to ArrayList<String[ ]>从 jtable 获取数据到 ArrayList<String[ ]>
【发布时间】:2017-07-27 15:41:15
【问题描述】:

我在从 JTable 获取数据时遇到问题。我需要将其保存到ArrayList&lt;String[]&gt;。我做了一个行和列的循环,但有些东西不起作用,它只保存最后一行......

这是函数示例:

private void saveTable(){

    ArrayList<String[]> tableSaved = new ArrayList<>();
    String[] rowSaved = new String[headerTable.length];
    String cellValue;

    for(int row=0;row<table.getModel().getRowCount();row++){
        for (int column=0; column<table.getModel().getColumnCount();column++){  
            cellValue = (String) table.getModel().getValueAt(row, column);
            rowSaved[column] = cellValue;

        }       
        tableSaved.add(rowSaved);
        // I check here if the output is correct, and It is.    
        System.out.println("GET");
        for(String s:rowSaved){
            System.out.print(s+" ");
        }
    }

    //When I check if the tableSaved is correct, It doesn't.
    System.out.println("");
    System.out.println("ACTUALLY SAVED");
    for (String[] row:tableSaved){          
        for (String s:){
            System.out.print(" "+s);
        }
        System.out.println("");
    }

我也试过这个循环

    int row=0;
    while (row<table.getModel().getRowCount()){ 
        int column=0;

        while (column<table.getModel().getColumnCount()){

            cellValue = (String) table.getModel().getValueAt(row, column);
            rowSaved[column] = cellValue;
            column++;
        }       
        tableSaved.add(rowSaved);
        row++;
    }

它返回最后一行的次数与表中的行一样多...我一直在寻找答案,但我没有解决这个错误

这是一个示例截图

【问题讨论】:

  • 我认为你需要添加 tableSaved.add(rowSaved);这在一个循环中。
  • 但它在第一个循环内...

标签: java swing arraylist jtable


【解决方案1】:

问题出在tableSaved.add(rowSaved); 您正在添加一个字符串数组,但您保留了该数组的引用,并且在下一次迭代中您正在更改同一数组的元素。

当您开始读取元素或将数组添加到ArrayList 之后,在循环内创建一个新的rowSaved = new Sting[]

tableSaved.add(rowSaved);之后添加这行rowSaved = new String[headerTable.length];

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-08-23
  • 1970-01-01
  • 2014-06-08
  • 1970-01-01
  • 1970-01-01
  • 2013-05-27
  • 2015-10-16
  • 1970-01-01
相关资源
最近更新 更多