15

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 store this information into a JTable. The problem is that i cant find a way to set a fixed number of rows

Here is my code:

Class 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 Class:

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;

   }

The SportsClub Class(abstract):

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

}

And finally, LeagueManager, which is an interface:

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

}

Can somebody please help me? I've trying and trying for days. Thank you.

jPratas
  • 225
  • 1
  • 6
  • 17

5 Answers5

28

"The problem is that i cant find a way to set a fixed number of rows"

You don't need to set the number of rows. Use a TableModel. A DefaultTableModel in particular.

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

Then you can add rows to the tableModel with an Object[]

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

tableModel.addRow(objs);

You can loop to add your Object[] arrays.

Note: JTable does not currently allow instantiation with the input data as an ArrayList. It must be a Vector or an array.

See JTable and DefaultTableModel. Also, How to Use JTable tutorial

"I created an arrayList from it and I somehow can't find a way to store this information into a JTable."

You can do something like this to add the data

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

}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Yes for your FootballClub – Paul Samsotha Dec 11 '13 at 19:10
  • so, it would be something like this: int max = Array.get(0); for ( int i = 1; i < array.length; i++) { if ( array.get(i) > max) { max = array.get(i); } } – jPratas Dec 11 '13 at 19:15
  • For what? For your getters? You getters should be in your `FootBallClub` and just need to return the data field value. `public int getPosition(){ return position; }` – Paul Samsotha Dec 11 '13 at 19:19
  • -1, doesn't make sense to create a FootballClub object and then immediately take the data from the FootballClub and create an Array of the data. If you want to use the DefaultTableModel then just load the data directly into the Array, or create a custom TableModel as suggested in the other answers. – camickr Dec 11 '13 at 19:20
  • @camickr you're right it doesn't but my example was not to imply doing that. I was just putting code together to show how it would look, since OP hasnt added any of the FootballClub objects to the list yet. – Paul Samsotha Dec 11 '13 at 19:23
  • @camickr your suggestion was my first thought but what if OP wants to keep that data in the list also? I was just following the flow of OPs code. – Paul Samsotha Dec 11 '13 at 19:25
  • `but what if OP wants to keep that data in the list also?` - there should not be 2 copies of the data, one in the List and one in the TableModel. The DefaultTableModel should only be used if you want all the data treated as independent data displayed together in a row. If you want your data treated as a FootballClub then you need to create a custom TableModel to support this. If you need all the FootballClubs returned in a List then you add a method to your TableModel to do this. – camickr Dec 11 '13 at 19:32
  • I have a small situation going on: how can I position the table in a certain position inside the layout? – jPratas Dec 11 '13 at 19:47
  • @peeskillet great answer. It worked great for me the only thing was that the label names for the Jtable didn't showed up. Cna you help with this ? I did it the exactly same way. – CodeEngine Jul 06 '15 at 20:39
10

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

How implements your own 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] ;
  }

}

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<FootballClub> clubs = getFootballClub();
TableModel model = new FootballClubTableModel(clubs);
JTable table = new JTable(model);

Hope it help !

NiziL
  • 5,068
  • 23
  • 33
  • On the part where you say complete here, it means i have to create the getPosition method, right? – jPratas Dec 11 '13 at 18:51
  • @jPratas In `getValueAt(int row, int col)`, you must return the element in the cell. So, if `col` = 0, you return the position of a football club, if `col` = 1, you return the team's name, if `col` = 2 the points, etc. This depends on which attribute of a football club you want to display on the column number `col`. Of course, you'll need getter like `getPosition()` or `getName()`... Perhaps you set the attributes as `public` to avoid getters, but isn't a good practice :) – NiziL Dec 11 '13 at 19:02
  • For this assignment, i had to use the SportsClub as an abstract class. I tested your way in a separate project and it works just fine. Thank you very much for your help :) – jPratas Dec 12 '13 at 01:36
  • very nice example easy to understand and small code. – Anand Kumar Jha Nov 17 '16 at 17:50
3

I created an arrayList from it and I somehow can't find a way to store this information into a JTable.

The DefaultTableModel doesn't support displaying custom Objects stored in an ArrayList. You need to create a custom TableModel.

You can check out the Bean Table Model. It is a reusable class that will use reflection to find all the data in your FootballClub class and display in a JTable.

Or, you can extend the Row Table Model found in the above link to make is easier to create your own custom TableModel by implementing a few methods. The JButtomTableModel.java source code give a complete example of how you can do this.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • +1 for `BeanTableModel` which I didn't know... Awesome trick ! – NiziL Dec 11 '13 at 18:46
  • For this assignment, I had to build the table within the java swing library. However, this answer was very useful and i will use this technology for future projects. Thank you :) – jPratas Dec 12 '13 at 01:34
0

You can do something like what i did with my List< Future< String > > or any other Arraylist, Type returned from other class called PingScan that returns List> because it implements service executor. Anyway the code down note that you can use foreach and retrieve data from the 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);
                    }
                }
Abdelsalam Shahlol
  • 1,621
  • 1
  • 20
  • 31
0

Basic method for beginners like me.

public void loadDataToJtable(ArrayList<String> liste){
        
    rows = table.getRowCount();

    cols = table.getColumnCount();

    for (int i = 0; i < rows ; i++) {

            for ( int k  = 0; k < cols ; k++) {
            
            for (int h = 0; h < list1.size(); h++) {
                
                String b =  list1.get(h);
                b = table.getValueAt(i, k).toString();
                
            }
        }
    }
}
ChrisF
  • 134,786
  • 31
  • 255
  • 325