[英]ArrayList items to JTable using DefaulTableModel
I am trying to take the contents inside my ArrayList, holding FootballClub objects and display them onto my JTable.我试图获取我的 ArrayList 中的内容,持有 FootballClub 对象并将它们显示到我的 JTable 上。 I can't seem to get this to work and I am not sure what I am doing wrong.
我似乎无法让它工作,我不确定我做错了什么。 Any help would be greatly appreciated.
任何帮助将不胜感激。 It says for model.add() that an array initializer is not allowed here.
它表示 model.add() 此处不允许使用数组初始值设定项。 My columnNames also seem to not be displaying
我的 columnNames 似乎也没有显示
// the arraylist containing footballclub objects
protected ArrayList<FootballClub> clubs = new ArrayList<FootballClub>();
public void displayTable(ArrayList<FootballClub> footballClubs)
{
String[] columnNames = {"Club name", "goals", "points", "wins"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
for(int i = 0; i < footballClubs.size(); i++)
{
String name = footballClubs.get(i).getClubName();
int goals = footballClubs.get(i).getGoals();
int points = footballClubs.get(i).getPoints();
int wins = footballClubs.get(i).getPoints();
model.addRow({{name, goals,points,wins}});
}
final JTable teamTable = new JTable(model);
teamTable.setFillsViewportHeight(true);
JFrame frame = new JFrame("Tableview");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(500, 500);
frame.setVisible(true);
}
You don't say how what you've written doesn't work.你不会说你写的东西怎么行不通。 I assume there is a compiler issue on this line:
我假设这一行存在编译器问题:
model.addRow({{name, goals,points,wins}});
It looks as if you are trying to use the Object[]
overload.看起来好像您正在尝试使用
Object[]
重载。 The correct syntax is:正确的语法是:
model.addRow(new Object[] { name, goals, points, wins });
Or, the special syntax for array initialisers:或者,数组初始值设定项的特殊语法:
Object[] row = { name, goals, points, wins} ;
model.addRow(row);
If there had been a List
overload, you could use List.of(name, goals, points, wins)
, but there isn't.如果有一个
List
重载,你可以使用List.of(name, goals, points, wins)
,但没有。
(Also note, it is conventional to use List
instead of ArrayList
. If there is a conflict with java.awt.List
you can explicitly add import java.util.List
. (另请注意,通常使用
List
而不是ArrayList
。如果与java.awt.List
存在冲突,您可以显式添加import java.util.List
。
The for
can be written: for
可以写成:
for (FootballClub club : footballClubs) {
which should make things clearer.)这应该使事情更清楚。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.