gpt4 book ai didi

java - ArrayList 输出到 JTable

转载 作者:行者123 更新时间:2023-12-02 05:53:15 24 4
gpt4 key购买 nike

是的,我已经用谷歌搜索过,是的,我已经阅读过,是的,我仍然陷入困境......

我有一个 ClassB 中的对象的 ArrayList,我通过调用 B 中 A 的方法返回到 ClassA 中的对象的 ArrayList。(相同的返回类型:)在 CLassB 中,我执行以下所有处理和存储:将对象属性放入类类型的对象数组中。

B类:

ClassB object = new ClassB();
ArrayList<ClassB> arrayOfObjects = new ArrayList<>();
int count = 0;
while(count<10){
///alot going on here but the general concept is this;
object.attribute1 = "something read in"
object.attribute2 = "something read in"
object.attribute3 = "something read in"
object.attribute4 = "something read in"
object.attribute5 = "something read in"

arrayOfObjects.add(object);
count++;

}

A类:

ArrayList<ClassB> arrayOfObjects = ClassBObject.method();



String[] columns = {"Column1","Column2","Column3", "Column4", "Column5"};

DefaultTableModel tableModel = new DefaultTableModel(columns, 0);

JTable table = new JTable(tableModel);

int i = 0;
while(i < arrayOfObjects.size()) {

//v for variable
String v1 = arrayOfObjects .get(i).attribute1;
String v2 = arrayOfObjects .get(i).attribute2;
String v3 = arrayOfObjects .get(i).attribute3;
String v4 = arrayOfObjects .get(i).attribute4;
String v5 = arrayOfObjects .get(i).attribute5;

Object[] row = {v1,v2,v3,v4,v5};

tableModel.addRow(row);
i++;
}
JFrame frame = new JFrame("Title of Table");

JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());

JScrollPane tableContainer = new JScrollPane(table);

panel.add(tableContainer, BorderLayout.CENTER);
frame.getContentPane().add(panel);

frame.pack();
frame.setVisible(true);

问题:使用上面的代码,表格仅显示最后一个对象,该对象重复执行 while 循环的次数。我想从对象数组中提取每个对象的属性,其中计数器用于匹配对象数组的元素。

我希望我足够详细,能够提供足够的背景知识来找到问题的根源。提前致谢!

最佳答案

好的,现在我们(可能)看到了您的问题!

ClassB object = new ClassB();
ArrayList<ClassB> arrayOfObjects = new ArrayList<>();
int count = 0;
while(count<10){
///alot going on here but the general concept is this;
object.attribute1 = "something read in"
object.attribute2 = "something read in"
object.attribute3 = "something read in"
object.attribute4 = "something read in"
object.attribute5 = "something read in"

arrayOfObjects.add(object);
count++;
}

您不必每次在循环中都重新创建一个新对象!

尝试:

// ***** don't create object *once* outside of the while loop!
// ClassB object = new ClassB();

ArrayList<ClassB> arrayOfObjects = new ArrayList<>();
int count = 0;
while(count<10){

// *** instead create a new one for each iteration of the loop!
ClassB object = new ClassB(); // *****************

///alot going on here but the general concept is this;
object.attribute1 = "something read in"
object.attribute2 = "something read in"
object.attribute3 = "something read in"
object.attribute4 = "something read in"
object.attribute5 = "something read in"

arrayOfObjects.add(object);
count++;
}

关于java - ArrayList 输出到 JTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23354103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com