pctripsesp
pctripsesp

Reputation: 53

getting data from jtable to ArrayList<String[ ]>

I'm having problems from getting data from a JTable. I need to save it to an ArrayList<String[]>. I do a loop of rows and columns but something is not working, it saves only the last row...

This is the function example:

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

I've tried this loop too

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

It returns the last row as many times as rows in the table... I've looking for an answer but I nothing solved the bug

This is an example screenshot

data from table returns

Upvotes: 1

Views: 1238

Answers (1)

ahoxha
ahoxha

Reputation: 1938

The problem is here tableSaved.add(rowSaved); you are adding an array of strings, but you are keeping the reference of that array, and in the next iteration you are changing elements of that same array.

Create a new rowSaved = new Sting[] inside the loop when you begin reading the elements or after you add the array into the ArrayList.

After the line tableSaved.add(rowSaved); add this line rowSaved = new String[headerTable.length];

Upvotes: 2

Related Questions