2013-12-11 15 views
12

Próbuję ustawić elementy z metody o nazwie FootballClub i jak na razie wszystko jest w porządku. , ale potem utworzyłem z niej listę arrayList i jakoś nie mogę znaleźć sposobu na zapisanie tej informacji w JTable. Problemem jest to, że nie mogę znaleźć sposób, aby ustawić stałą liczbę wierszyWczytywanie danych array array do JTable

Oto mój kod:

Klasa StartLeague:

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 
    } 
    } 

Football Club Klasa:

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 ligowy, który jest interfejsem:

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ś mógłby mi pomóc? Próbowałem i próbowałem przez kilka dni. Dziękuję.

+0

Nie sądzę, że JTable przyjmuje ArrayList jako argument danych. Potrzebujesz także Vector lub 2d array –

+0

również, obecnie twoja ArrayList będzie pusta, ponieważ tworzysz nowe kluby piłkarskie, ale nie dodajesz ich do listy. – DoubleDouble

Odpowiedz

19

„Problemem jest to, że nie mogę znaleźć sposób, aby ustawić stałą liczbę wierszy”

Nie trzeba ustawić liczbę wierszy. Użyj numeru TableModel. A w szczególności: DefaultTableModel.

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żna dodać wiersze do tableModel z Object[]

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

tableModel.addRow(objs); 

Można pętli, aby dodać Object [] tablic.

Uwaga: JTable obecnie nie zezwala na tworzenie danych wejściowych jako ArrayList. Musi to być Vector lub tablica.

Zobacz JTable i DefaultTableModel. Również How to Use JTable tutorial

„I stworzył ArrayList z nim i jakoś nie mogę znaleźć sposób przechowywania tych informacji w JTable."

można 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); 

} 
+0

oznacza to, że muszę stworzyć wszystkie metody pobierania, prawda? – jPratas

+0

Tak dla twojego FootballClub –

+0

, więc byłoby coś takiego: int max = Array.get (0); dla (int i = 1; i max) { max = array.get (i); } } – jPratas

8

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

Jak realizuje 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 zastąpić inne metody TableModel, zależy od tego, co chcesz zrobić, ale tutaj jest zasadnicze sposoby, aby zrozumieć i wdraża :)
Używaj go jak ten

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

nadzieję, że to pomoże!

+0

W części, w której powiesz, że jest to pełne, oznacza to, że muszę utworzyć metodę getPosition, prawda? – jPratas

+0

@jPratas W 'getValueAt (int row, int col)' musisz zwrócić element w komórce. Tak więc, jeśli 'col' = 0, zwrócisz pozycję klubu piłkarskiego, jeśli' col' = 1, zwrócisz nazwę drużyny, jeśli 'col' = 2 punkty, itd. To zależy od tego, który atrybut piłki nożnej Klub, który chcesz wyświetlić na kolumnie numer "col". Oczywiście, będziesz potrzebował gettera, jak 'getPosition()' lub 'getName()' ... Być może ustawiłeś atrybuty jako 'public', aby uniknąć pobierających, ale nie jest to dobra praktyka :) – NiziL

+0

Do tego zadania, Musiałem użyć SportsClub jako klasy abstrakcyjnej. Przetestowałem twoją drogę w oddzielnym projekcie i działa dobrze. Dziękuję bardzo za pomoc :) – jPratas

2

Stworzyłem z niej tablicęList i nie mogę znaleźć sposobu na zapisanie tej informacji w JTable.

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

Możesz sprawdzić numer Bean Table Model. Jest to klasa wielokrotnego użytku, która użyje refleksji, aby znaleźć wszystkie dane w klasie FootballClub i wyświetlić je w JTable.

Można również przedłużyć Row Table Model znaleziony w powyższym łączu, aby ułatwić tworzenie własnego niestandardowego modelu TableModel za pomocą kilku metod. Kod źródłowy JButtomTableModel.java podaje pełny przykład tego, jak możesz to zrobić.

+0

+1 za "BeanTableModel", którego nie znałem ... Niesamowita sztuczka! – NiziL

+0

Do tego zadania musiałem zbudować tabelę w bibliotece java swing. Jednak ta odpowiedź była bardzo przydatna i wykorzystam tę technologię do przyszłych projektów. Dziękuję Ci :) – jPratas

0

Można zrobić coś, co zrobiłem z moim listy < Future < String>> lub inny ArrayList, Typ wrócił z drugiej klasy o nazwie PingScan która zwraca List> ponieważ realizuje wykonawcę usług. W każdym razie, zanotuj kod, że możesz użyć foreach i pobrać dane z List.

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); 
        } 
       }