Prerequisites:
Download and Install Net Beans IDE: https://netbeans.org/
Download Jasper report Library: https://sourceforge.net/projects/jasperreports/
Download Org-apache-commons-loggin.jar, commons-digester.jar, commons-collections.jar and commons-beanutils.jar files and add them to the libraries.
Procedure
Step 1: Create a Java Application
Create a Java with Ant Application, Provide a Project Name and make sure to uncheck Create Main Class.
Step: 2: Add a Button
I added a button and renamed the text to “Run Report”
Step 3: Add JAR file references
Add JAR file references to the application.
Under Libraries > Add JAR/Folder and add all the JAR files from dist folder as shown below:
Step 3: Download all the jar files
Org-apache-commons-loggin.jar, commons-digester.jar, commons-collections.jar and commons-beanutils.jar files and add them to the libraries and add them to the libraries path
Please see above screenshot as a reference to the libraries that I have added to my project.
In addition, you need to add database JAR file to the project.
Since I was using Postgres Data source, I downloaded the postgresql-42.6.0.jar file and added that to library.
Step 4: Create the Report in TIBCO Jaspersoft® Studio
In Jaspersoft Studio, I created a simple report that selects fields from a table from MySQL Datasource.
Select * from a table and I have added the fields to the report
Saved it and exported to file. Say this file name is “Sample_report.jrxml” file.
I saved this file to C:TempSample_report.jrxml on my desktop.
Step 5: Create a Click Event
I double clicked on the Button to create a click event
Added the following code:
try { Class.forName("org.postgresql.Driver"); try (Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/foodmart790", "postgres", "postgres")) { String reportPath = "C:\Temp\Sample_report.jrxml"; JasperReport jr = JasperCompileManager.compileReport(reportPath); JasperPrint jp = JasperFillManager.fillReport(jr, null, con); JasperViewer.viewReport(jp); } } catch (Exception ex) { ex.printStackTrace(); }
Importing :
import java.sql.Connection;import java.sql.DriverManager;import net.sf.jasperreports.engine.JasperFillManager;import net.sf.jasperreports.engine.JasperPrint;import net.sf.jasperreports.engine.JasperReport;import net.sf.jasperreports.engine.JasperCompileManager;import net.sf.jasperreports.view.JasperViewer;
Step 6: Run report
Finally, when I click the play button, a window pops up that says Run report.
When I click on the button. Jasper Report is compiled filled and printed in to the Jasper viewer.
As shown in below screenshot:
Note:
You may run into a warning message while executing the report:
- Video example