从 jtable 获取数据到 ArrayList<String[ ]>
getting data from jtable to ArrayList<String[ ]>
我在从 JTable 获取数据时遇到问题。我需要将它保存到 ArrayList<String[]>
。我做了一个行和列的循环,但有些东西不起作用,它只保存最后一行......
这是函数示例:
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++;
}
它 returns 最后一行与 table 中的行一样多......我一直在寻找答案,但我没有解决错误
这是示例屏幕截图
问题出在这里tableSaved.add(rowSaved);
您正在添加一个字符串数组,但您保留了该数组的引用,并且在下一次迭代中您正在更改同一数组的元素。
当您开始读取元素或将数组添加到 ArrayList
后,在循环内创建一个新的 rowSaved = new Sting[]
。
在行 tableSaved.add(rowSaved);
之后添加此行 rowSaved = new String[headerTable.length];
我在从 JTable 获取数据时遇到问题。我需要将它保存到 ArrayList<String[]>
。我做了一个行和列的循环,但有些东西不起作用,它只保存最后一行......
这是函数示例:
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++;
}
它 returns 最后一行与 table 中的行一样多......我一直在寻找答案,但我没有解决错误
这是示例屏幕截图
问题出在这里tableSaved.add(rowSaved);
您正在添加一个字符串数组,但您保留了该数组的引用,并且在下一次迭代中您正在更改同一数组的元素。
当您开始读取元素或将数组添加到 ArrayList
后,在循环内创建一个新的 rowSaved = new Sting[]
。
在行 tableSaved.add(rowSaved);
之后添加此行 rowSaved = new String[headerTable.length];