0

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

使用我在这里找到的示例,我能够在我的报告中获得一个自定义数据源。

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

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 不允许动态添加到该 Object 数组,并且由于报告数据总是动态的,因此它变得无用。

我已经尝试了一个自定义数据类,其中包含我添加到 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.");
    }

}

任何帮助都会很棒。

4

1 回答 1

1

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

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();
    }
}
于 2012-07-23T20:16:15.367 回答