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

Advertisements

Running Client part of Java Enterprise Application using a batch file

Below is a simple way of running the client part of a J2EE application, by creating a batch file. Some assumtions made are :

1. JDK is installed on the Computer

2. Glassfish is installed and the EJB module deployed

To create a batch file, open notepad.exe, type your need commands and save your file as filename.bat

Below is the content of the batch file

Rem the portion below starts the Glassfish server if it has been shutdown

cd C:\Sun\SDK\lib
call “C:\Sun\SDK\config\asenv.bat”
call “%AS_INSTALL%\bin\asadmin.bat” start-domain domain1

goto e

Rem the portion below call the jar file, by going to its directory and

Rem calling the full class name (including package name of the start up file

:e
cd c:\
cd C:\sabon\eduSSS
set APPCPATH=.\
appclient -client EducationSSSClient.jar -mainclass com.sabonay.educationSss.ui.LoginForm
goto end

:end

Below is a picture after running the script

scriptspage

 

Binding a JComboBox to a List

Here is a method to bind a list to a combo box.

Hope it will be helpful

public ComboBoxModel cityModel(List<cityDetail>cityList ) {
ComboBoxModel model;

if (cityList == null || cityList.size() <= 0) {
Object[] d = new Object[1];
//d[0] = “None”;
ComboBoxModel mo = new DefaultComboBoxModel(d);
return mo;
}

Object[] days = new Object[cityList.size() + 1];
int i = 0;
try {
ListIterator<CityDetails> lg = cityList.listIterator();
while (lg.hasNext()) {
CityDetails newcus = lg.next();
days[i] = newcus.getCityname();
i = i + 1;
}

days[i] = “Add New”;
} catch (Exception ex) {
System.out.println(“error occured ” + ex.toString());
}
model = new DefaultComboBoxModel(days);
return model;
}
this.cbCity.setModel(cityModel())

//where cbCity is the jcombobox

Populating a JTable with a Collection (List)

Below is a method for populating a Jtable using a List(Collection)

Hope it will be helpful


private void DisplayData(List<productdetail>ProductsList) {
DefaultTableModel aModel = new DefaultTableModel() {
//setting the jtable read only

@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
//setting the column name
Object[] tableColumnNames = new Object[2];
tableColumnNames[0] = “Product Name”;
tableColumnNames[1] = “Description”;

aModel.setColumnIdentifiers(tableColumnNames);
if (ProductsList == null) {
this.tbProducts.setModel(aModel);
return;
}

Object[] objects = new Object[2];
ListIterator<productsdetail> lstrg = ProductsList.listIterator();
//populating the tablemodel
while (lstrg.hasNext()) {
productsdetail newcus = lstrg.next();
objects[0] = newcus.getProductName();
objects[1] = newcus.getDescription();

aModel.addRow(objects);
}

//binding the jtable to the model
this.tbProducts.setModel(aModel);
}

Creating MDI Applications in Java Using Netbeans

This is a simple process for Java users who want to create Multiple Document Interface Applications in Java. The application makes use of JPanels , a JFrame and a JDesktopPane.

To start with, all your child forms should be created using panels (JPanels) as the container. A frame is then created as the parent form. A desktop pane is then added to the frame to be container for the panels on the JFrame.

Below is how the application Works

1.   Create your child forms on a panel

2.   Create a frame and add a desktoppane to it as shown below

main

The black color is showing the JDesktopPane. You can set the “Anchor” and “Auto Resizing” properties of the DesktopPane so that it fits the desired size of your choice.

Add the method below to your Frame Class

public void addFrame(JPanel panel, String title) {

try {

JInternalFrame[] children = jDesktopPane1.getAllFrames();

//creating a new internal frame from the Panel passes as parameter

internalframe j = new internalframe(panel, title);

//checking to see if the child form already exist

for (JInternalFrame f : children) {

if (f.getTitle().equals(j.getTitle())) {

f.setSelected(true);

return;

}

}

//adding a new child

jDesktopPane1.add(j);

j.setVisible(true);

j.setSelected(true);

} catch (PropertyVetoException ex) {

Logger.getLogger(mainxpframe.class.getName()).log(Level.SEVERE, null, ex);

}

}

To show the child forms add the code below to the button click event

customersdetailpanel sd=new customersdetailpanel();

sd.setSize(750, 600);

addFrame(sd, "Customers Information");

the “customersdetailpanel” is one of the child forms.

Below is an interface showing showing the MDI Application

sub

Hope this will be helpful

SAVING IMAGES IN A DATABASE USING EJBS

It is sometimes troublesome to save and retrieve images in  a database using java. Below are methods that are useful in saving and retrieving images from a database

To save an image in a database the datatype of the column should be “blob”. One thing to note is that in the EJBs the blob datatype is change to an array of bytes (“byte[]”)

A function to change an image file into its bytes

public Function byte[] setImagebytes(File imageFile) {

byte[] imagebytes = null;

try {

FileInputStream fis = new FileInputStream(imageFile);

imagebytes = new byte[(int) imageFile.length()];

fis.read(imagebytes);

} catch (FileNotFoundException ex) {

ex.printStackTrace();

} catch (IOException ex) {

ex.printStackTrace();

}

Return imagebytes;

}

A method to browse for an image file from its location and show it in a label

private void btBrowseActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

// a method to browse for a picture and pass the image file to the setImagebytes method

fc.setFileFilter(new FileNameExtensionFilter("Images", "jpg", "gif", "bmp"));

if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {

fc.setCurrentDirectory(fc.getCurrentDirectory());

ImageIcon icon = new ImageIcon(fc.getSelectedFile().getAbsolutePath());

icon = new ImageIcon(icon.getImage().getScaledInstance(150, 150, Image.SCALE_DEFAULT));

this.lbPicture.setIcon(icon);

//passing the image file to the setImagebytes to create the image bytes

this.setImagebytes(fc.getSelectedFile());

//icon.getImage()

repaint();

}

}

A method to convert the bytes array (byte[]) into a pictures to display in a label

Private void getRealImage(byte[] imagebytes){

if (imagebytes != null) {

ImageIcon icon = new ImageIcon(imagebytes);

icon = new ImageIcon(icon.getImage().getScaledInstance(150, 150, Image.SCALE_DEFAULT));

this.lbPicture.setIcon(icon);

} else {

ImageIcon icon = new ImageIcon();

//showing the image in a label

this.lbPicture.setIcon(icon);

}

}