Java 将 arrayList 数据加载到 JTable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20526917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:33:16  来源:igfitidea点击:

Load arrayList data into JTable

javaswingarraylistjtablegrid-layout

提问by jPratas

I'm trying to set items from a method called FootballCluband 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

我正在尝试从一个被调用的方法中设置项目,FootballClub到目前为止一切正常。但后来我从它创建了一个 arrayList,但不知何故我找不到将这些信息存储到 JTable 中的方法。问题是我找不到设置固定行数的方法

Here is my code:

这是我的代码:

Class StartLeague:

类 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):

SportsClub 类(摘要):

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:

最后是 LeagueManager,它是一个接口:

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.

有人能帮帮我吗?我已经尝试了好几天了。谢谢你。

采纳答案by Paul Samsotha

"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 DefaultTableModelin particular.

您不需要设置行数。使用一个TableModel. 一个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);

Then you can add rows to the tableModelwith an Object[]

然后你就可以行到添加tableModelObject[]

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

tableModel.addRow(objs);

You can loop to add your Object[] arrays.

您可以循环添加 Object[] 数组。

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

注意:JTable 目前不允许将输入数据实例化为ArrayList. 它必须是一个Vector或一个数组。

See JTableand DefaultTableModel. Also, How to Use JTable tutorial

请参阅JTableDefaultTableModel。另外,如何使用 JTable 教程

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

“我从它创建了一个 arrayList,但不知何故我找不到将这些信息存储到 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);

}

回答by NiziL

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

您可能需要使用TableModel此处为 Oracle 教程

How implements your own TableModel

如何实现你自己的 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

您可能需要覆盖 的其他方法TableModel,这取决于您想要做什么,但这里是理解和实现的基本方法:)
像这样使用它

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

Hope it help !

希望有帮助!

回答by camickr

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

我从它创建了一个 arrayList,但不知何故无法找到将此信息存储到 JTable 中的方法。

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

DefaultTableModel 不支持显示存储在 ArrayList 中的自定义对象。您需要创建一个自定义的 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.

您可以查看Bean Table Model。它是一个可重用的类,它将使用反射来查找您的 FootballClub 类中的所有数据并显示在 JTable 中。

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

或者,您可以扩展Row Table Model上述链接中的内容,通过实现一些方法来更轻松地创建您自己的自定义 TableModel。该JButtomTableModel.java源代码给你如何能做到这一个完整的例子。

回答by Abdelsalam Shahlol

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 foreachand retrieve data from the List.

您可以执行类似于我对List< Future< String > >或任何其他 Arraylist, Type 执行的操作,该 Type 从其他名为 PingScan 的类返回,该类返回 List> 因为它实现了服务执行程序。无论如何,代码注释您可以使用foreach并从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);
                    }
                }