Hello,
This topic is intended to inform, step by step, how to create a report with iReport and run it through a java application.
For better understanding, it will work with the project in a layer structure, all files will be in the root folder of the project.
• Tools used:
• iReport-1.2.5• Java (version jre1.5.0_06)
• Eclipse (Lomboz)
• MySQL 5.0.18
MySQL Backup
Source Host: localhost
Source Server Version: 5.0.18-nt
Source Database: meuprojeto
Date: 2006/11/29 21:27:23
*/
SET FOREIGN_KEY_CHECKS=0;
#----------------------------
#----------------------------
`cod` int(11) NOT NULL auto_increment,
`descricao` varchar(50) character set latin1 collate latin1_general_ci default NULL,
`preco` double default NULL,
PRIMARY KEY (`cod`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
#----------------------------
# Records for table tb_produtos
#----------------------------
insert into tb_produtos values
(1, 'camisa', '20'),
(2, 'calça', '30'),
(3, 'perfume', '70'),
(4, 'cinto', '20'),
(5, 'sapato', '100'),
(6, 'cueca', '10'),
(7, 'teste', '10');
We have created the schema, table and some records, we will open the iReport to create the report:
Open iReport and if you do not have an active connection, follow the steps below:
• In the menu, click Data and then Connectio / Datasources, you will have a screen like this:
• Click new and set as pictured below:
• If the User requires root password, enter it in PassWord
• Click Test to verify the connection and then click Save.
• You return pala the previous window, select the connection and click Set as Default.
• Close the window
Let's create the report as quickly and practice
• Click File Report Wizard
• In the report to query for the report, as stated:
Click Next on the next window, place all items to the right window, as shown and click Next
• We will sort by group, click Next again
• In the next window, select Tabular Layout and classicT.xml, as shown:
•Clique em Next e em Encerrar
Voce terá algo assim:
Locate these buttons
The first compiles the report, the second shows the structure (no data) and the third displays the report with the data.
If you have not saved the report, anyone that you click, it will ask to save, do this and name the report.
Make some tests with the buttons, if the report is not displayed, check the previous steps as this point, you should see the report ready.
If it did all right, let's change the title, double click on it and change to the Dangerous Goods, see:
and stay that way.
Save the report again and close the iReport.
Remember that the report was saved with the extension. Jrxml?Well, this file is usually used for editing the report, but what we use is what led to the iReport extençsão. Jasper.
Verify that it is already in the folder where you installed the iReport later, when we are creating a Java application, they must be copied to the root of the project. At the opportune time to remind you ...
At this point we already have the report ready, let's create the application.
At this point, are not necessary the views of images, just inform you that files should be created (from substance), which will be saved and other files to be copied, ok?
Open Eclipse, create a new java project named ProjRelatorio.
With the project selected, click the right mouse button and click New, and Folder, then name it lib Above all, we will bring the package files for the iReport project.
Go to the lib directory of iReport and copy the following files to the lib folder of your project.
Check the image:
Note that the last file mysql-connector-java-3.1.12-bin.jar may have a different version than you find in the lib folder, no problem.
Files copied? We will inform the project that they exist.
• With the project selected click Project Properties
• In the window that opens click Java Build Path
• Libraries Select window and click Add JARs
• Expand without project, click the lib folder, select all the files, click OK and OK again.
public class ExcRepositorio extends Exception {public ExcRepositorio(String mensagem) {super(mensagem);}}
Save as: gConexao.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class gConexao {
private static Connection con;
public static Connection getConexao() throws ExcRepositorio {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/meuprojeto";
String login = "root";
String senha = "";
try {
Class.forName(driver);
con = DriverManager.getConnection(url, login, senha);
} catch (ClassNotFoundException e) {
throw new ExcRepositorio("Driver não encontrado: " + e.getMessage());
} catch (SQLException e) {
throw new ExcRepositorio("Erro abrindo conexão: " + e.getMessage());
}
return con;
}
}
Save as: principal.java
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;
public class principal {
public static void main(String[] args) throws JRException {
repositorioProduto rep = new repositorioProduto();
JasperPrint relat;
//Insere mais um produto e exibe o relatório
String desc = JOptionPane.showInputDialog("Descrição do produto: ");
double valor = Double.parseDouble(JOptionPane.showInputDialog("Valor: "));
produto prod = new produto(desc,valor);
try {
rep.inserir(prod);
relat = rep.gerar();
JasperViewer.viewReport(relat, false);
} catch (ExcRepositorio e) {
JOptionPane.showMessageDialog(null, "Erro: " + e.getMessage());
}
}
}
Save as: produto.java
public class produto {
private int cod;
private String descricao;
private double preco;
public produto(String desc, double preco){
this.setDescricao(desc);
this.setPreco(preco);
}
public int getcod() {return cod;}
public String getDescricao() {return descricao;}
public double getPreco() {return preco;}
public void setcod(int cod) {
this.cod = cod;
}
public void setDescricao(String desc){
this.descricao = desc;
}
public void setPreco(double pc){
this.preco = pc;
}
}
Save as: repositorioProduto.java
import java.sql.Connection;We will now copy the files relatorio.jrxml and relatorio.jasper iReport folder to the root folder of your project (only need the. Jasper, but leave a copy of jxml as security.).
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
public class repositorioProduto{
public repositorioProduto() {}
public void inserir(produto prod) throws ExcRepositorio{
String desc = prod.getDescricao();
double preco = prod.getPreco();
String SQL = "insert into tb_Produtos (descricao, preco) values " +
"('" + desc + "', " + preco + ")";
Connection conn = null;
Statement stat = null;
try {
conn = gConexao.getConexao();
stat = conn.createStatement();
stat.executeUpdate(SQL);
} catch (SQLException e) {
throw new ExcRepositorio("Erro na conexão ao inserir: " + e.getMessage());
} finally {
if (stat != null) {
try {
stat.close();
} catch (SQLException e) {
throw new ExcRepositorio("Erro ao fechar conexão: " + e.getMessage());
}
}
}
}
public JasperPrint gerar() throws ExcRepositorio{
JasperPrint rel = null;
try {
Connection con = gConexao.getConexao();
HashMap map = new HashMap();
String arquivoJasper = "relatorio.jasper";
rel = JasperFillManager.fillReport(arquivoJasper, map, con);
} catch (JRException e) {
JOptionPane.showMessageDialog(null,e.getMessage());
}
return rel;
}
}
Phew! Now just run, you are prompted to insert data from a product, do this and I see it included in the report that will be displayed.











Nenhum comentário:
Postar um comentário