CREATING SIMPLE HELP FILES IN JAVA

In this post, we are to discuss how to create help for your swing application using swing components. The idea is to create text file for each help file, the content can be formatted with html, then on click of a button you display a particular file in a panel. To make the panel (help page) stay on top of other opened windows of your application we can choose to display it as a dialog.check https://gilbertadjin.wordpress.com/2009/10/21/form-showdialog-in-java/ how to show a panel as dialog.

To start with we create a class that will load a help file from a source(which you have save it in the settings of your application) by passing the file name without the extension….below is the class

   1: import java.io.File;

   2: import java.util.logging.Level;

   3: import java.util.logging.Logger;

   4: import javax.swing.JOptionPane;

   5: import org.apache.commons.io.FileUtils;//download org.apache.commons.io.FileUtils

   6: public class helpFile {

   7:     private String helpContent = null;

   8:     public helpFile(String filename) {

   9:        try {

  10:             //loading the help file from  a location stored in your settings

  11:             File file=new File(Settings.loadProperties().getProperty("xp.helpsource") +"/"+ filename +".txt");

  12:                         if (file.exists()) {

  13:                 helpContent = FileUtils.readFileToString(file);

  14:             } else {  

  15:                 JOptionPane.showMessageDialog(null, "File Does not Exist \n" + file.getPath() + "\n" + file.toString());

  16:             }

  17:         } catch (Exception ex) {

  18:             Logger.getLogger(helpFile.class.getName()).log(Level.SEVERE, null, ex);

  19:         }

  20:     }

  21:     @Override

  22:     public String toString() {

  23:         return helpContent;

  24:     }

  25: }

Then we create a panel and name it “helpdetailPanel”. We then add a JEditorPane to the Panel and then add the constructor below to the panel class

   1: public helpdetailpanel(String text) {

   2:         initComponents();

   3:         this.editor.setContentType("text/html");

   4:         this.editor.setText(text);    

   5:     }

Then in the application,on click of a button we add the code below to show a help based on the name (help file name) we pass to the “helpfile” class. Below shows the code to show the panel with the help content

   1: //helpfile is the class to load the help file from its source

   2:    helpdetailpanel hd = new helpdetailpanel(new helpFile("customers").toString());

   3:    hd.setSize(700, 700);

   4:    popupsjdialog d = new popupsjdialog(null, hd, true);

   5:    d.setVisible(true);

In the code above, “customers” is the name of a help file with a content below.

   1: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

   2: <html>

   3: <head>

   4: " "

   5: </head>

   6: <body>

   7: <span style="" bold=""

   8:  text-decoration="" underline="">&nbsp;<span

   9:  style="font-weight: bold; text-decoration: underline;">CUSTOMER

  10: INFORMATION</span> </span>

  11: <br>

  12: <br>

  13: 1. To &nbsp;add a new Customer click on the add new button. Enter <br>

  14: &nbsp; &nbsp; &nbsp;the required information and click on

  15: Save<br>

  16: <br>

  17: 2. To Edit a Customer select it from the table view, make the changes

  18: required and click on Save<br>

  19: <br>

  20: 3. To delete a Customer, select it from the table view, and click on

  21: the delete button<br>

  22: </body>

  23: </html>

The picture below shows how the help content that is displayed at runtime on click of a help button in the Customers Panel.

image

Cheers  !!!!!!!!!!!

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 !!!

LOAD IMAGES DYNAMICALLY INTO JASPER REPORTS

If you want to insert images from the file system (e.g. C:\images folder) into jasper reports at runtime, for example changing a logo depending on user selection or simply allowing the user to browse for his or her image to be displayed  in the report then here is a simple process of doing that.

Let start with the report design using ireport. In this instance the picture will be passed to the report as a parameter.

So let’s create a parameter in our report and call it “photo”

image

As shown in the picture above, the data type of our parameter should be “java.lang.Object”

After this, drag the image , from the tool bar, on to your report.Right click on the image and choose “Properties” from the menu

image

Under the image tab of the dialog box, make sure you select “java.awt.image” for the Image Expression Class. Once this is done, you are done with the report design

Lets go to netbeans , do some coding and connect our designed report to a java application.

First we need to declare a variable of type image,

Image photo;

Also we create a method , which on click of a button, loads a picture from the file system and initializes the “photo: variable.

JFileChooser fc = new JFileChooser();

private void getPicture() {

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(350, 350, Image.SCALE_DEFAULT));

photo = icon.getImage();

}

After getting our picture, create an instance of the Map class and pass our “variable” as a parameter.

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

param.put("photo", photo); //the “photo” should be the same name as the parameter name in our report

We then create a method that passes our created parameter to the report and we are done. below is the method that does the job.

private void generateReports(String name, Map param) {

try {

String source = "C:/sabonay/jasperreports/" + name + ".jrxml";

if (new File(source).exists() == false) {

xputils.showMessage("Please  report Source does not exist");

return;

}

JasperReport jasperReport = JasperCompileManager.compileReport(source);

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, param, new JREmptyDataSource());

JasperViewer.viewReport(jasperPrint, false);

//the false parameter makes sure the application does not close on closing the report

} catch (Exception e) {

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

}}

Make sure to reference the necessary jasper jar files in your application

STRINGS IN JAVA

“Wow !!!! Now Thus Intereeessssting” That was how i exclaimed when i saw these interesting features of the STRING class in java. All this while when i wanted to convert a character array to a string , i had to go through a loop. For example

String password = “” ;
char[] pass = this.txtPassword.getPassword();
for (int i = 0; i < pass.length; i++) {
password = password + pass[i];
}

But this char[] pass can easily be converted to string by just a line of code:

char[] pass = this.txtPassword.getPassword();
String password=new String(pass);

Also another interesting feature of the string class is that you can easily get the string value out of a byte array and vice versa with so much ease. check this.

byte[] array=”sdfdfd”.getBytes();
String string=new String(array);

These are not all, there are more interesting features, exploree!!!!

Fellows, enjoy the weekend

FORM.SHOWDIALOG() IN JAVA

Have you wondered how to show a panel(form) as a dialog in java applications as done in .NET applications by using the form.showDialog() method?  For example, when a user selects “Add New” from a Customer combobox, the customer panel shows as a dialog for a new entry before the user can continue. If you have been searching for this, here is your stop.

We will be making use of one JDialog, and your FORMS(JPanels in this sense).

To implement this add a JDialog to your application. Declare a variable contentPane and add the constructor like the one specified below.

private Container contentPane = null;

public popupsjdialog(java.awt.Frame parent, JPanel panel, boolean modal) {
//super(parent, modal);
contentPane = this.getContentPane();
initComponents();
this.setSize(panel.getSize().width + 30, panel.getSize().width + 50);
panel.setLocation(10, 30);
contentPane.add(panel);
repaint();
this.setLocationRelativeTo(null);

}

Your are now done. Now to show any JPanel as a dialog add the following code to your event.

helpdetailpanel hd = new helpdetailpanel(helpContent);
hd.setSize(700, 700);
popupsjdialog d = new popupsjdialog(null, hd, true);
d.setVisible(true);

Helpdetailpanel is a Jpanel (form) you want to show as a dialog and the popupsjdialog is an instance of the Jdialog we created its constructot above.

Cheers !!!!!!!!!!!!!!!!!

READING EXCEL FILES IN JAVA APPLICATIONS

Have you wondered about how to read excel files(.xls,xlsx), in Java Applications without using any API, then here is your stop. With this you can read excel 2003 and also 2007.We will be going through simple steps in reading the content of excel files and populating it into a Jtable. We will be working in the Microsoft Windows environment.

First, you have to create a datasource pointing to where your excel file is located. To do this, Go to Control panel ——— >   Administrative Tools ———- > Data Sources (ODBC). Below is an interface you are likely to see.

datasource face

Select the “User DSN” tab and click on the add button and select the driver “Microsoft Excel Driver (.xls,xlsx)” . You will be presented with the interface below, enter the name of the data source (Note, this is the name you will reference from you Java Application) and click on the “Select Workbook” button to select the excel file you want to read. You are now done with setting up the datasource.

choose driverselect workbook

Let’s now go to our Jave IDE (Netbeans) and do some small coding.  We will be using the JDBC-ODBC driver for reading our data. You don’t need to add the driver to your application as Windows OS comes with the Driver already installed.

We are creating a simple application where the user enters the datasource name and the sheet name, then on click of a button the data if populated into a JTable

 

We do this by creating a method

private void GetData(String excelDSN, String sheetname) {

        Connection connection = null;

        Statement st;

        ResultSet rsltSet;

        ResultSetMetaData rsltSetMetaData;

        String excelURL = "jdbc:odbc:" + excelDSN;

        String query = "Select * from [" + sheetname + "$]";

 

        try {

            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            connection = DriverManager.getConnection(excelURL);

            //System.out.println("ReadExcel connection = " + connection);

            st = connection.createStatement();

            //System.out.println("ReadExcel connection.createStatement() = " + st);

            rsltSet = st.executeQuery(query);

            //System.out.println("ReadExcel rsltSet = " + rsltSet);

            rsltSetMetaData = rsltSet.getMetaData();

           

          //creating a datamodel for our JTable

            DefaultTableModel aModel = new DefaultTableModel() {

                @Override

                //setting the JTable uneditalble

                public boolean isCellEditable(int row, int column) {

                    return false;

                }

            };

            //adding the excel column names to the JTable

            Object[] tableColumnNames = new Object[rsltSetMetaData.getColumnCount()];

            for (int i = 1; i <= rsltSetMetaData.getColumnCount(); i++) {

                tableColumnNames[i-1] = rsltSetMetaData.getColumnName(i);

            }

            aModel.setColumnIdentifiers(tableColumnNames);

            //adding the rows to the JTable

            Object[] objects = new Object[rsltSetMetaData.getColumnCount()];

            while (rsltSet.next()) {

                for (int i = 1; i <= rsltSetMetaData.getColumnCount(); i++) {

                    objects[i-1] = rsltSet.getObject(i);

                }

                aModel.addRow(objects);

            }

            // setting the table model of the jtable

            this.jTable1.setModel(aModel);

        } catch (Exception ex) {

            JOptionPane.showMessageDialog(null, ex.toString() );

        }

    }

Note , In reading records from excel, the index starts from one not zero(0). Once you starting getting this exception “[Microsoft][ODBC Driver Manager] Invalid descriptor index.” Get the index , its 1 not zero

Sample interface of the Application

the app

CREATING A JASPER REPORT WITHOUT A DATASOURCE

If you want to generate jasper reports in your JAVA applications without using a data source, then here is your stop. For example printing receipts directly from user inputs, where all you need are parameters. Also this piece talks about how to insert images from the file system ( hard drives pen dirves) into jasper reports at runtime.It assumed you know how to generate reports with jasper reports. This help was created using Netbeans 6.7 and iReport 3.5.2

Relax and Enjoy!!!!!!!!!!!!!!!

In this our example, we are creating a report that requires a name, hometown and a picture from the user at runtime to be displayed on our report. Design your report by creating the parameters; name as string, hometown as string and picture as object. With the name and hometown parameters, you can drag them onto the report interface, but for the image, drag  the image item from the tool bar and bind it to the picture parameter. Below is a picture of the report

the report designed in iReport

After this, go to Netbeans and do some simple coding. Below are the methods needed to run your application. Make sure to add the Jasper jar files to your application

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

// a method to generate the report, by assigning the prameter to their value, and calling te generate report method

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

param.put("name", this.tfName.getText());

param.put("hometown", this.tfHometown.getText());

param.put("photo", photo);

generateReports("report1", ls, param);

}

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

// a mehod t browse for an image to be inserted into te report

//photo is a variable of type image

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(350, 350, Image.SCALE_DEFAULT));

photo = icon.getImage();

}

}

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

//a method to generate th report

try {

String source = "C:/sabonay/jasperreports/" + name + ".jrxml";

if (new File(source).exists() == false) {

xputils.showMessage("Please go report file does not exst");

return;

}

JasperReport jasperReport = JasperCompileManager.compileReport(source);

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, param, new    JREmptyDataSource());

JasperViewer.viewReport(jasperPrint, false);

} catch (Exception e) {

e.printStackTrace();

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

}

}

Below are pictures after running theappliation

using entering parameter values
Sample report generated