问题
Hi how can I copy data from my JTable into an ArrayList? I dont want the first row which is the columns name, I want everyother row. Thanks
回答1:
If you are storing the data in the table with out using any object then just traverse row by row on the table and get every object and store it in the List.
Example: This is when you are using a list to store the data.
List<Object> list = new ArrayList<Object>;
for(int row = 0; row < table.getRowCount(); row++) {
for(int column = 0; column = table.getColumnCount(); column++) {
list.add(table.getValueAt(row, column));
}
}
Finally you will get all the objects in the list.
EDIT:
Since each row is an object of type CustomObject we need to set each value of the table to the object of type CustomObject and add it to the List for every row.
class CustomObject {
Object one;
Object two;
}
List<CustomObject> list = new ArrayList<CustomObject>;
for(int row = 0; row < table.getRowCount(); row++) {
CustomObject object = new CustomObject();
for(int column = 0; column = table.getColumnCount(); column++) {
switch(column) {
case 0:
object.setOne(table.getValueAt(row, column));
break;
case 1:
object.setTwo(table.getValueAt(row, column));
break;
}
}
// Store each object in the list.
list.add(object);
}
回答2:
The preferred, and robust, way is using the TableModel. Use JTable.getModel() to get it. Once you have a TableModel, you can use its API to know what value it has at any location using getValueAt(int rowIndex, int columnIndex) and then store it in you List.
来源:https://stackoverflow.com/questions/59337803/can-i-put-my-data-from-my-jtable-into-a-arraylist