Załaduj dane arrayList do JTable

Próbuję ustawić elementy z metody o nazwie FootballClub i jak na razie jest dobrze. ale potem stworzyłem z niego arraylistę i jakoś nie mogę znaleźć sposobu na przechowywanie tych informacji w JTable. Problem polega na tym, że nie mogę znaleźć sposobu na ustawienie stałej liczby wierszy

Oto Mój kod:

Klasa:

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;

public class startLeague implements LeagueManager{

//setting the frame and other components to appear

public startLeague(){
    JButton createTeam = new JButton("Create Team");
    JButton deleteTeam = new JButton("Delete Team");

    JFrame frame = new JFrame("Premier League System");
    JPanel panel = new JPanel();
    frame.setSize(1280, 800);
    frame.setVisible(true);
    frame.add(panel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    String col[] = {"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};

    panel.setLayout(new GridLayout(20, 20));
    panel.add(createTeam);
    panel.add(deleteTeam);
    panel.add(new JLabel(""));
    //JLabels to fill the space
    }
    }

Klasa Klubu Piłkarskiego:

import java.util.ArrayList;



 public class FootballClub extends SportsClub{





   FootballClub(int position, String name, int points, int wins, int defeats, int draws, int totalMatches, int goalF, int goalA, int goalD){
   this.position = position;
   this.name = name;
   this.points = points;
   this.wins = wins;
   this.defeats = defeats;
   this.draws = draws;
   this.totalMatches = totalMatches;
   this.goalF = goalF;
   this.goalA = goalA;
   this.goalD = goalD;

   }

Klasa SportsClub(streszczenie):

abstract class SportsClub {
int position;
String name;
int points;
int wins;
int defeats;
int draws;
int totalMatches;
int goalF;
int goalA;
int goalD;

}

I wreszcie, LeagueManager, który jest interfejs:

import java.util.ArrayList;


public interface LeagueManager {
ArrayList<FootballClub> originalLeagueTable = new ArrayList<FootballClub>();
FootballClub arsenal = new FootballClub(1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19);
FootballClub liverpool = new FootballClub(2, "Liverpool", 30, 9, 3, 3, 15, 34, 18, 16);
FootballClub chelsea = new FootballClub(3, "Chelsea", 30, 9, 2, 2, 15, 30, 11, 19);
FootballClub mCity = new FootballClub(4, "Man City", 29, 9, 2, 4, 15, 41, 15, 26);
FootballClub everton = new FootballClub(5, "Everton", 28, 7, 1, 7, 15, 23, 14, 9);
FootballClub tot = new FootballClub(6, "Tottenham", 27, 8, 4, 3, 15, 15, 16, -1);
FootballClub newcastle = new FootballClub(7, "Newcastle", 26, 8, 5, 2, 15, 20, 21, -1);
FootballClub south = new FootballClub(8, "Southampton", 23, 6, 4, 5, 15, 19, 14, 5);

}
Czy ktoś może mi pomóc? Próbuję i próbuję od kilku dni. Dziękuję.
Author: jPratas, 2013-12-11

4 answers

"problem polega na tym, że nie mogę znaleźć sposobu na ustawienie stałej liczby wierszy"

Nie musisz ustawiać liczby wierszy. Użyj TableModel. A DefaultTableModel w szczególności.

String col[] = {"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};

DefaultTableModel tableModel = new DefaultTableModel(col, 0);
                                            // The 0 argument is number rows.

JTable table = new JTable(tableModel);

Następnie możesz dodać wiersze do {[5] } za pomocą Object[]

Object[] objs = {1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19};

tableModel.addRow(objs);

Możesz w pętli dodać tablicę obiektu [].

Uwaga: JTable nie zezwala obecnie na tworzenie instancji z danymi wejściowymi jako ArrayList. To musi być Vector lub tablica.

Zobacz JTable i DefaultTableModel . Ponadto, Jak korzystać z JTable tutorial

"stworzyłem z niego arraylistę i jakoś nie mogę znaleźć sposobu na przechowywanie tych informacji w JTable."

Możesz zrobić coś takiego, aby dodać dane

ArrayList<FootballClub> originalLeagueList = new ArrayList<FootballClub>();

originalLeagueList.add(new FootballClub(1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19));
originalLeagueList.add(new FootballClub(2, "Liverpool", 30, 9, 3, 3, 15, 34, 18, 16));
originalLeagueList.add(new FootballClub(3, "Chelsea", 30, 9, 2, 2, 15, 30, 11, 19));
originalLeagueList.add(new FootballClub(4, "Man City", 29, 9, 2, 4, 15, 41, 15, 26));
originalLeagueList.add(new FootballClub(5, "Everton", 28, 7, 1, 7, 15, 23, 14, 9));
originalLeagueList.add(new FootballClub(6, "Tottenham", 27, 8, 4, 3, 15, 15, 16, -1));
originalLeagueList.add(new FootballClub(7, "Newcastle", 26, 8, 5, 2, 15, 20, 21, -1));
originalLeagueList.add(new FootballClub(8, "Southampton", 23, 6, 4, 5, 15, 19, 14, 5));

for (int i = 0; i < originalLeagueList.size(); i++){
   int position = originalLeagueList.get(i).getPosition();
   String name = originalLeagueList.get(i).getName();
   int points = originalLeagueList.get(i).getPoinst();
   int wins = originalLeagueList.get(i).getWins();
   int defeats = originalLeagueList.get(i).getDefeats();
   int draws = originalLeagueList.get(i).getDraws();
   int totalMatches = originalLeagueList.get(i).getTotalMathces();
   int goalF = originalLeagueList.get(i).getGoalF();
   int goalA = originalLeagueList.get(i).getGoalA();
   in ttgoalD = originalLeagueList.get(i).getTtgoalD();

   Object[] data = {position, name, points, wins, defeats, draws, 
                               totalMatches, goalF, goalA, ttgoalD};

   tableModel.add(data);

}
 20
Author: Paul Samsotha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-11 18:58:56

Prawdopodobnie musisz użyć TableModel (Oracle ' s tutorial here )

Jak zaimplementować własne TableModel

public class FootballClubTableModel extends AbstractTableModel {
  private List<FootballClub> clubs ;
  private String[] columns ; 

  public FootBallClubTableModel(List<FootballClub> 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] ;
  }

}

Być może trzeba nadpisać inne metody TableModel, zależy od tego, co chcesz zrobić, ale oto podstawowe metody do zrozumienia i wdrożenia:)
Użyj go w ten sposób

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

Mam nadzieję, że to pomoże !

 8
Author: NiziL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-11 18:52:44

Stworzyłem z niego arraylistę i jakoś nie mogę znaleźć sposobu na przechowywanie tych informacji w JTable.

DefaultTableModel nie obsługuje wyświetlania niestandardowych obiektów przechowywanych w ArrayList. Musisz utworzyć niestandardowy model tabeli.

Możesz sprawdzić model stołu fasolowego . Jest to klasa wielokrotnego użytku, która użyje reflection, aby znaleźć wszystkie dane w klasie FootballClub i wyświetlić je w tabeli JTable.

Lub możesz rozszerzyć Row Table Model Znalezione w powyższy link ułatwia stworzenie własnego niestandardowego modelu TableModel poprzez wdrożenie kilku metod. Kod źródłowy JButtomTableModel.java daje pełny przykład jak możesz to zrobić.

 2
Author: camickr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-11 18:42:52

Możesz zrobić coś takiego jak ja z moją List > lub inną Arraylist, typu zwracanego z innej klasy o nazwie PingScan, która zwraca List> ponieważ implementuje service executor. W każdym razie kod w dół zauważ, że możesz użyć foreach i pobrać dane z listy .

 PingScan p = new PingScan();
 List<Future<String>> scanResult = p.checkThisIP(jFormattedTextField1.getText(), jFormattedTextField2.getText());
                for (final Future<String> f : scanResult) {
                    try {
                        if (f.get() instanceof String) {
                            String ip = f.get();
                            Object[] data = {ip};
                            tableModel.addRow(data);
                        }
                    } catch (InterruptedException | ExecutionException ex) {
                        Logger.getLogger(gui.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
 0
Author: Abdelsalam Shahlol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-07 06:00:51