javaswinglistjtable

Populate JTable Using List


How will I populate a JTable with values from a List with an Object Type. My Code looks like this :

String[] columnNames = {"CLASS CODE",
        "TIME",
        "DAY",
        "ROOM",
        "PROFESSOR"};

    List<org.mine.ScheduleAttr> schedule = getStudSched(studNo);
    DefaultTableModel model = new DefaultTableModel();
    table.setModel(model);

    model.setColumnIdentifiers(columnNames);

I already have the columns, the list would come from the schedule variable ? How can I put that to my table considering these columns ?


Solution

  • Take a look at DefaultTableModel. You could iterate over your List and create the Object array for each row.

    for (ScheduleAttr s : schedule) {
      Object[] o = new Object[5];
      o[0] = s.getX();
      o[1] = s.getY();
      o[2] = s.getZ();
      o[3] = s.getA();
      o[4] = s.getB();
      model.addRow(o);
    }