我必须使用ArrayList
填充JTable
,但是当表格显示时,它填充了其他内容,但不是正确的信息。您可以通过单击下一个链接来查看我的表格的外观。
gui1
是主类的名称,theObject
是包含要在表格上显示的信息的结构的类的名称。
请帮我解决这个问题!!
ArrayList
定义:
static ArrayList<theObject> datos = new ArrayList<theObject>();
这是用于加载名为“datos”的ArrayList的代码:
try {//------------------------------------ 项目注册库 ----------------------------------------
contador = 0;
fr = new FileReader(file);
br = new BufferedReader(fr);
while ((cadena1 = br.readLine()) != null){
datos1 [0] = cadena1.substring(0,8);
datos1 [1] = cadena1.substring(8,38);
datos1 [2] = cadena1.substring(38,52);
datos1 [3] = cadena1.substring(52,57);
datos1 [4] = cadena1.substring(57,62);
datos1 [5] = cadena1.substring(62,72);
datos1 [6] = cadena1.substring(72,77);
datos1 [7] = cadena1.substring(77,82);
datos1 [8] = cadena1.substring(82,89);
datos1 [9] = cadena1.substring(89,94);
datos1 [10] = cadena1.substring(94,239);
datos.add(new theObject(datos1));
contador ++;
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
该表填充有以下行:
tabla = new JTable(new MyModel(datos));
现在代码中涉及的类:
class theObject {
String sap,cte,pep,dis1,dis2,norma,nvent,ntc,tmando,tparalel,equip;
theObject(String dato[]) {
this.sap = dato[0];
this.cte = dato[1];
this.pep = dato[2];
this.dis1 = dato[3];
this.dis2 = dato[4];
this.norma = dato[5];
this.nvent = dato[6];
this.ntc = dato[7];
this.tmando = dato[8];
this.tparalel = dato[9];
this.equip = dato[10];
}
}
class MyModel extends AbstractTableModel {
private String[] columnNames = { "FERT","CLIENTE ","PEP","A","B","C","D","E","F","G","H" };
ArrayList<theObject> arr1 = null;
MyModel(ArrayList<theObject> arr1) {
this.arr1 = arr1;
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return pru2.datos.size();
}
public Object getValueAt(int row, int col) {
theObject a1 = datos.get(row);
return a1;
}
}
在 Eclipse 中编译后没有错误,所以我无法识别问题
最佳答案
您为每个单元格获取 gui$theObject@4ab60e21
的原因是因为您在 getValueAt()
中返回整个 theObject
,它应该只返回 theObject
的字段,例如,您的类如下所示
public class TheObject { // please notice the Naming convention
// and follow it. Class begins with capital
private fert;
private cliente;
private pep;
// getter and setters
}
您在 getValueAt()
中的值应该只返回基于 col 的字段之一。例如
private String[] columnNames = { "FERT","CLIENTE ","PEP" };
private ArrayList<TheObject> data;
...
public Object getValueAt(int row, int col) {
Object value = null;
TheObject obj = data.get(row);
switch(col) {
case 0: value = obj.getFert(); break;
case 1: value = obj.getCliente(); break;
case 2: value = obj.getPep(); break;
default: break;
}
return value;
}
因此,您的单元格值将只是 TheObject
的一个字段,而不是整个 TheObject
对象。
关于java - JTable 由 ArrayList 填充,结果不好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24815875/