TABLEMODEL AS DATASOURCE IN JASPER REPORTS

It is a common requirement in many J2SE (client,swing) applications to present data in a tabular way and also print this tabular format as a report.

Jasper reports provides implementation that makes the task of generating reports from tabular formats simple in Swing
applications. In this demonstrations, we will be using Jasper reports 3.6.1, Netbeans 6.1 and Ireport 3.6.1.

Let start by designing our report. In generating reports from tablemodels the report fields must match the column names of the tablemodel, but sometimes it becomes impractical to use the actual column names as report fields. Jasper Reports provides a way to generate reports from TableModels without having to map the actual table columns to the report fields. We can name our
report fields COLUMN_X, where x is the column index, starting with zero. Note “COLUMN” all characters should be capitals as “column” will give you error message at run time.

Also in case you have 3 columns in your table and you define a report field “COLUMN_4” , which is for column 5, null values will be displayed for each row in the report under that field. To prevent null values from displaying in a text field you can edit the expression for that field e.g. (($F{COLUMN_4}==null)? "":$F{COLUMN_4}.toString()), which means if the if the value of $F{COLUMN_4} is null ,display nothing else display the value. To do this, right click the text field and select “edit expression”, an expression editor will pop up for you to change the expression.

Below is a picture of our report at design time

image

After creating our report, we go to our application (using Netbeans as the IDE), we add a JTable and a JButton to our JFrame. We the create a method which accepts  the table model to create the report, tbProducts is the name of the Jtable. Check https://gilbertadjin.wordpress.com/2009/05/05/populating-a-jtable-with-a-collection-list/ to see how to populate a list of javabean object to a Jtable

private void generateReports(String name, Map param) {
        try {

      String source = "C:/sabonay/jasperreports/" + name + ".jrxml";
            if (new File(source).exists() == false) {
      xputils.showMessage("Please go to setting and Choose report Source");
                return;
            }

JasperReport jasperReport = JasperCompileManager.compileReport(source);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, param, new JRTableModelDataSource(tbProducts.getModel()));

            JasperViewer.viewReport(jasperPrint, false);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("reports Error  " + e.toString());

        }

Cheers !!!

Advertisements

CREATING JASPER REPORTS WITH DYNAMIC IMAGES

This is a tutorial on how to embed images stored in a database (javaDB, MySQL,etc) into a jasper repors at runtime. This tutorial uses EJBs for creating an object for the table and its fields from the database. I’m also using Collection (List) of objects as the data source for the jasper reports. It is assumed the reader knows how to create reports using jasper reports.

The image field in the database table can be of data type blob, medium blob or long blob. In our entity class for the table, the datatype of the image (photo) field will be of the type byte [].Note that the image that will be sent to the report will be a type of java.awt.image, so therefore we create one additional field of type image in our class. In your code, create a method that converts a blob to image. (This can easily be done using image icon, as it accept blob and you can get image from it as well)

We will be using ireport 3.0, Netbeans 6.5 , Sun Application Server( because of me using session beans, but will not be necessary when creating desktop applications) as the development environment. Make sure to add the jasper report libraries to your projects.

Design your report by creating the necessary fields in the ireport.  Make sure the names of the field are the same as they appear in the entity class (the datasource) including capitalization as shown below

report1

In creating the fields, the image (photo) field should be of the type Object. After creating the image field, insert an image into your report from the ireport toolbar.  Then bind the image to the image (photo) field then you are done with the design of your report.

report3

Save your report. Note that the file type of your report can be .jrxml or .jasper. I’m using the .jasper as it removes the overhead of compiling it in your code in case it is .jrxml

Then you go to netbeans to do some small coding.

Write the code below under an actionevent

generateReports("StudentDetail", reportFactory.returnStudentsBySchool(s.getSchID()), param);

the “studentdetail” is the name of the report file, “param” is a map object which is used  incase you are filling part of your report with parameters (usually user imput). Parameters are also created the same way as creating fields but under the parameters section

Exxample of creating a map object in java

Map<String, Object> param = new HashMap<String, Object>();

param.put("school", “Abakrampa”); //school is the name of the parameter as it in the report inteface

“returnStudentsBySchool(s.getSchID())” is a method that returns a collection of the object (our datasource, and this is the detail

public static Collection returnStudentsBySchool(int schid) {

educationSSSSessionRemote session = lookupnewEducateFacadeBean();//session beans

List data = null;

List<StudentDetail> results = null;

data = session.findStudentBySchool(schid);// returns the students object with blob

ListIterator<StudentDetail> lstmb = data.listIterator();

results = new ArrayList<StudentDetail>();

// converting the byte[] to image type for all the student objects

ImageIcon n;

while (lstmb.hasNext()) {

StudentDetail s = lstmb.next();

if (s.getPicture() != null) {

n = new ImageIcon((byte[]) s.getPicture());

} else {

n = new ImageIcon();

}

s.setPhoto(n.getImage(),

results.add(s);

}

return results;

}

The generate report method

private void generateReports(String name, Collection data, Map param) {

try {

URL urlfilename = null;

String oSource = "reports/" + name;

String rSource = "reports/" + name + ".jasper";

urlfilename = getClass().getResource(rSource);

String reportfile = null;

if (urlfilename != null) {

reportfile = urlfilename.getPath();

} else {

return;

}

JRBeanCollectionDataSource jrbc = new JRBeanCollectionDataSource(data);

JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile, param, jrbc);

JasperViewer.viewReport(jasperPrint, false);//"

// when the false is absent on closing the report it closes your java apllication

} catch (Exception e) {

e.printStackTrace();

System.out.println("reports Error  " + e.toString());

}   }

Below is a sample report when the app is run

report4