A Simple Java Desktop JasperReport Example

Hi, im currently testing the latest version of iReport, iReport 4.5.1. For the test, im trying to create a very simple reporting, consist of 2 column and without database connection. Im using a simple Array of Maps to fill my jasper report’s data using the JRMapCollectionDataSource class.

Here is my report example,

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
	<property name="ireport.zoom" value="1.0"/>
	<property name="ireport.x" value="0"/>
	<property name="ireport.y" value="0"/>
	<field name="name" class="java.lang.String"/>
	<field name="address" class="java.lang.String"/>
	<background>
		<band splitType="Stretch"/>
	</background>
	<title>
		<band height="31" splitType="Stretch">
			<staticText>
				<reportElement x="235" y="0" width="100" height="31"/>
				<textElement>
					<font size="24"/>
				</textElement>
				<text><![CDATA[Judul Saya]]></text>
			</staticText>
		</band>
	</title>
	<pageHeader>
		<band height="35" splitType="Stretch"/>
	</pageHeader>
	<columnHeader>
		<band height="22" splitType="Stretch">
			<staticText>
				<reportElement x="0" y="2" width="100" height="20"/>
				<textElement/>
				<text><![CDATA[name]]></text>
			</staticText>
			<staticText>
				<reportElement x="200" y="2" width="100" height="20"/>
				<textElement/>
				<text><![CDATA[address]]></text>
			</staticText>
		</band>
	</columnHeader>
	<detail>
		<band height="20" splitType="Stretch">
			<textField>
				<reportElement x="0" y="0" width="200" height="20"/>
				<textElement/>
				<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="200" y="0" width="221" height="20"/>
				<textElement/>
				<textFieldExpression><![CDATA[$F{address}]]></textFieldExpression>
			</textField>
		</band>
	</detail>
	<columnFooter>
		<band height="13" splitType="Stretch"/>
	</columnFooter>
	<pageFooter>
		<band height="14" splitType="Stretch"/>
	</pageFooter>
	<summary>
		<band height="8" splitType="Stretch"/>
	</summary>
</jasperReport>

Dont forget to compile it, and this is my java code to call my report. It call for .jasper file instead of .jrxml files.

package com.edw.main;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import org.apache.log4j.Logger;

public class Main {

    private Logger logger = Logger.getLogger(Main.class);

    public Main() {
    }

    private void start() {
        try {                                            
            // load report location
            FileInputStream fis = new FileInputStream("report.jasper");
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fis);

            // fill report
            List<Map<String,?>> maps = new ArrayList<Map<String, ?>> (); 
            for (int i = 0; i < 10; i++) {
                Map<String,Object> map = new HashMap<String, Object>();
                map.put("name", getRandomString());
                map.put("address", getRandomString());
                maps.add(map);
            }            
            JRMapCollectionDataSource dataSource = new JRMapCollectionDataSource(maps);
            
            // compile report
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap(), dataSource);

            // view report to UI
            JasperViewer.viewReport(jasperPrint, false);

        } catch (Exception e) {
            logger.error(e, e);
        }
    }
    
    private String getRandomString(){
        return UUID.randomUUID().toString();
    }

    public static void main(String[] args) {
        Main main = new Main();
        main.start();
    }
}

And some screenshots from my project,

Have fun with Jasper Report ;)

Google+

12 Comments

exnesian

about 5 years ago

Why can't I post reply on this thread: http://edwin.baculsoft.com/2010/09/a-simple-java-client-server-application-using-ejb3-and-glassfish3/ I always got "You have failed the challenge!". I am sure not that bad in math!

Reply

edwin

about 5 years ago

yes, sometime the challenge is a little bit annoying. But without challenge, my blog would be full of spams and unwanted comments :D

Chandan

about 4 years ago

un: log4j:WARN No appenders could be found for logger (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory). log4j:WARN Please initialize the log4j system properly. net.sf.jasperreports.engine.JRException: org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 449; cvc-complex-type.3.2.2: Attribute 'uuid' is not allowed to appear in element 'jasperReport'. at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:239) at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:222) at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:210) at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:199) at jasperreportswing.JasperReportSwing.actionPerformed(JasperReportSwing.java:69) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252) at java.awt.Component.processMouseEvent(Component.java:6505) at javax.swing.JComponent.processMouseEvent(JComponent.java:3321) at java.awt.Component.processEvent(Component.java:6270) at java.awt.Container.processEvent(Container.java:2229) at java.awt.Component.dispatchEventImpl(Component.java:4861) at java.awt.Container.dispatchEventImpl(Container.java:2287) at java.awt.Component.dispatchEvent(Component.java:4687) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422) at java.awt.Container.dispatchEventImpl(Container.java:2273) at java.awt.Window.dispatchEventImpl(Window.java:2713) at java.awt.Component.dispatchEvent(Component.java:4687) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707) at java.awt.EventQueue.access$000(EventQueue.java:101) at java.awt.EventQueue$3.run(EventQueue.java:666) at java.awt.EventQueue$3.run(EventQueue.java:664) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87) at java.awt.EventQueue$4.run(EventQueue.java:680) at java.awt.EventQueue$4.run(EventQueue.java:678) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:677) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105) at java.awt.EventDispatchThread.run(EventDispatchThread.java:90) Caused by: org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 449; cvc-complex-type.3.2.2: Attribute 'uuid' is not allowed to appear in element 'jasperReport'. at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198) at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(XMLSchemaValidator.java:449) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(XMLSchemaValidator.java:3228) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.processAttributes(XMLSchemaValidator.java:2705) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:2047) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:737) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:376) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:602) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3063) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:881) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123) at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210) at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568) at org.apache.commons.digester.Digester.parse(Digester.java:1647) at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:235) ... 40 more

edwin

about 4 years ago

hi Chandan, try to downgrade the version of your jasper report, or change the name variable "UUID" into something else, "UUIDX" perhaps :)

Handra

about 5 years ago

What's fis? whether such a class? I use iReport as well, its what the library is in need of anything?

Reply

edwin

about 5 years ago

hi Handra, i think fis is a variable for FileInputStream, please see my netbeans project screenshot. It shows the libraries needed for the application to running smoothly.

zaloe

about 5 years ago

hey can i ask for the project, i really need to master this kind of project, coz i want to make a project that can generate report without DB connection

Reply

edwin

about 5 years ago

Hi zaloe, you can copy the sourcecode written here. You can use JRMapCollectionDataSource or JRBeanCollectionDataSource, for handling jasperreport's data without relying on DB connection. Terima Kasih :D

Venkat

about 5 years ago

When used the above code it's giving as many pages as iterator. For example in the above i<10, it's giving 10 pages rather than 10 rows but in the above report it's given rows. Why it's not happening to rows.

Reply

edwin

about 5 years ago

Hi Venkat, perhaps it's because there's some mistakes on jrxml file. Try creating jrxml report with iReport instead.

Sree

about 5 years ago

Hello Edwin, how could you test this code in iReport ? Can you please post the class and static function which you had created for providing Java Bean Datasource iReport ? I'm using iReport 3.1 (as my production server supports jrxmls created from this version only). Although I'm passing the Maps and required key value pairs in them, iReport displays a null for all the fields. It however shows as many number of rows in the report as the the number of maps in the report.

Reply

edwin

about 5 years ago

Hi Sree, Java Bean Datasource use javabean as its primary rows, try set the bean's property as iReport's column.

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked


:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)