Load arrayList data into JTable

后端 未结 4 514
无人及你
无人及你 2020-11-29 05:16

I\'m trying to set items from a method called FootballClub and so far it\'s fine. but then I created an arrayList from it and I somehow can\'t find a way to sto

4条回答
  •  暖寄归人
    2020-11-29 06:14

    You probably need to use a TableModel (Oracle's tutorial here)

    How implements your own TableModel

    public class FootballClubTableModel extends AbstractTableModel {
      private List clubs ;
      private String[] columns ; 
    
      public FootBallClubTableModel(List aClubList){
        super();
        clubs = aClubList ;
        columns = new String[]{"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};
      }
    
      // Number of column of your table
      public int getColumnCount() {
        return columns.length ;
      }
    
      // Number of row of your table
      public int getRowsCount() {
        return clubs.size();
      }
    
      // The object to render in a cell
      public Object getValueAt(int row, int col) {
        FootballClub club = clubs.get(row);
        switch(col) {
          case 0: return club.getPosition();
          // to complete here...
          default: return null;
        }
      }
    
      // Optional, the name of your column
      public String getColumnName(int col) {
        return columns[col] ;
      }
    
    }
    

    You maybe need to override anothers methods of TableModel, depends on what you want to do, but here is the essential methods to understand and implements :)
    Use it like this

    List clubs = getFootballClub();
    TableModel model = new FootballClubTableModel(clubs);
    JTable table = new JTable(model);
    

    Hope it help !

提交回复
热议问题