gpt4 book ai didi

java - 将对象的 ArrayList 转换为 jasperreports 的对象数组

转载 作者:行者123 更新时间:2023-12-01 15:15:55 25 4
gpt4 key购买 nike

好的。这是一个新手大问题,但我一直在徒劳地寻找解决方案。

使用我找到的示例 here我能够在我的报告中使用自定义数据源。

但是......该示例将这段代码用于作为数据传递的实际对象

private Object[][] data =
{
{"Berne", new Integer(22), "Bill Ott", "250 - 20th Ave."},
{"Berne", new Integer(9), "James Schneider", "277 Seventh Av."},
{"Boston", new Integer(32), "Michael Ott", "339 College Av."},
{"Boston", new Integer(23), "Julia Heiniger", "358 College Av."}, etc...

不幸的是,java 不允许动态添加到该对象数组,并且由于报告数据始终是动态的,因此它变得毫无用处。

我尝试了一个自定义数据类,其中包含两个元素,我将它们添加到 ArrayList 中,例如

ArrayList<myDataObject> a = new ArrayList<myDataObject>();

for(int x=0;x<5;x++){
myDataObject myl = new myDataObject("asdasd",Integer.toString(x));
a.add(myl);
}

但是(这是 newbee 部分)我似乎无法弄清楚如何将其转换为 jasper 期望的简单 Object[][]。

这是我正在使用的数据类

import java.util.ArrayList;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;

public class CustomData implements JRDataSource {

private Object data[][];
private int index;


// public CustomData(Object o[][]) {
// index = -1;
// this.data = o;
// }
public CustomData(ArrayList <Object> a) {
index = -1;
this.data = (Object)a.toArray();
}

public boolean next() throws JRException {
index++;
return (index < data.length);
//throw new UnsupportedOperationException("Not supported yet.");
}

public Object getFieldValue(JRField field) throws JRException {
Object value = null;
String fieldName = field.getName();

if ("aName".equals(fieldName)) {
value = data[index][0];
}
else if ("aNumber".equals(fieldName)) {
value = data[index][1];
}

return (String)value;
// throw new UnsupportedOperationException("Not supported yet.");
}

}

任何帮助都会很棒。

最佳答案

简单地迭代列表并将其添加到二维数组中就会想到:

public static void main(String[] args) {
ArrayList<MyDataObject> a = new ArrayList<MyDataObject>();

for(int x=0;x<5;x++){
MyDataObject myl = new MyDataObject("asdasd", Integer.toString(x));
a.add(myl);
}

int aSize = a.size();
Object[][] thingy = new Object[aSize][2];
for(int i = 0; i < aSize; i++) {
MyDataObject mdo = a.get(i);
thingy[i][0] = mdo.getS();
thingy[i][1] = mdo.getI();
}
}

关于java - 将对象的 ArrayList 转换为 jasperreports 的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11619482/

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