Copy Data from JTable into ArrayList

徘徊边缘 提交于 2019-12-31 07:42:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!