20 July 2012

String Class

String Class

Hello Friends, Nice to see you again.
After lots of post related to Java Swing, Here, I come with core java part.

String is the class which is mostly used in every java based applications.
We can say that java applications can not be imagined without the String Class.... :)

Here we will discuss the core feature of String class.
So sit tight for unforgoettable journey of Java String Class....

Strings Are Immutable Objects:

In Java, each character in a string is a 16-bit Unicode character. Because Unicode characters are 16 bits (not the skimpy 7 or 8 bits that ASCII provides), a rich, international set of characters is easily represented in Unicode.

In Java, strings are objects. Just like other objects, you can create an instance of a String with the new keyword, as follows:
String s = new String();

This line of code creates a new object of class String, and assigns it to the reference variable s. So far, String objects seem just like other objects. Now, let's give the String a value:
s = "abcdef";


As you might expect, the String class has about a zillion constructors, so you can use a more efficient shortcut:

String s = new String("abcdef");

And just because you'll use strings all the time, you can even say this:
String s = "abcdef";

What they have in common is that they all create a new String object, with a value of "abcdef", and assign it to a reference variable s. Now let's say that you want a second reference to the String object referred to by  s:

String s2 = s; // refer s2 to the same String as s

Here you feel nothing special right..? But the word Immutability! comes here in play
(What the heck is immutability?)....

Once you have assigned a String a value, that value can never change— it's immutable, frozen solid, won't budge, fini, done.

The good part is that though the String object is immutable, its reference variable is not.

Lets understand with the example:

s = "abcdef";
s = s.concat(" more stuff");  // the concat() method 'appends'
               // a literal to the end

Here as we said earlier, String is immutable, then what the heck is this --- appending old string..!
This is the tricky part of String Class. Here please pay attention how VM behaves...!

First ,the value s contains was "abcdef", then we append it and now VM add " more stuff" at the end.
Now new String will be ""abcdef more stuff".

Now  At this point in our example, we have two String objects: the first one we created, with the value "abcdef", and the second one with the value "abcdef more stuff".

Here ehat happened....we assigned s to s2 earlier then we append s with " more stuff".
If we did not assign s to s2 then after append s the old String "abcdef" would be lost in memory...
Surprise...! This is because when you append the old String object with adding new String at the end of it. It will create another new String with old String + new appended String.
And the older value will be lost in memory without any reference variable. 
Look the below image for better understanding of working of String in Memory...


The above figure shows what happens on the heap when you reassign a reference variable. Note that the dashed line indicates a deleted reference.

To review our first example:

String s = "abcdef"; // create a new String object, with value "abcdef", refer s to it
String s2 = s; // create a 2nd reference variable referring to the same String
// create a new String object, with value "abcdef more stuff",
// refer s to it. (Change s's reference from the old String to the new String.) 
//( Remember s2 is still  referring to  the original "abcdef" String.)
// s = s.concat(" more stuff");

So this is how String is really Immutable....

Note: Please do not use String in you code where too much updation and modification in String is required...In thiat case use StringBuilder Class.

--------------------------------------------------------------------

So I hope this post is helpful in understanding Of String Class.

Feel free to ask me if you have any dought regarding this.
You can also give me suggessions to improve this post.

Leave comments if you like this post...!

Thank you.
Nirav Raval

2 January 2012

Import Excel Data into JTable

Import Excel Data into JTable

Hello Friends,

Nice to see you again. This post is the requirement which is asked from my fellow friends amongst you..
In Previous Sessions  we have seen the examples related to JTable with excel and jTable with MySQL database.

Here We will reverse the previous JTable example of export JTable data into Excel sheet.. 
We will create one Window which  will ask from user for import excel file.

After click on Select Excel File button, fileChooser will be opened and User 
has to select only Excel file and the excel sheet data will be displayed in JTable.

As there is no such direct method which provide you this facility at once.
So we have to write some sort of code to enable of filling JTable with Data from Excel file.

It is very easy to understand the code for this. When you run the code following will be output:



Here in above window, user will see nothing but one button for asking Excel file. Just click on that button and you will see fpllowing:



Here is the jFilechooser, from this you have to choose excel file having extension ".xls".  Otherwise following Error message will be displayed:

Note: If you want to go with MS Office 2007 Excel, you have to customise this code little bit.
Now  after select excel file the data in that Excel file will be shown in JTable as below:

OK For this you have to create one class called  excelTojTable.java 
and paste the below code in it.

And run it....Simple right..?

Note: In this code All the Dynamic Part logic is done in 
              fillData()  method.  So focus on that method...

Note:    To run this example successfully you have to download and add "jxl.jar" file.


import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import jxl.Cell;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class excelTojTable extends JFrame {

 static JTable table;
 static JScrollPane scroll;
 // header is Vector contains table Column
 static Vector headers = new Vector();
 // Model is used to construct JTable
 static DefaultTableModel model = null;
 // data is Vector contains Data from Excel File
 static Vector data = new 
   Vector();
 static JButton jbClick;
 static JFileChooser jChooser;
 static int tableWidth = 0; // set the tableWidth
 static int tableHeight = 0; // set the tableHeight

 public excelTojTable() {
  super("Import Excel To JTable");
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  JPanel buttonPanel = new JPanel();
  buttonPanel.setBackground(Color.white);
  jChooser = new JFileChooser();
  jbClick = new JButton("Select Excel File");
  buttonPanel.add(jbClick, BorderLayout.CENTER);
  // Show Button Click Event
  jbClick.addActionListener(new ActionListener() {

   @Override
   public void actionPerformed(ActionEvent arg0) {
    jChooser.showOpenDialog(null);
    
    File file = jChooser.getSelectedFile();
    if(!file.getName().endsWith("xls")){
     JOptionPane.showMessageDialog(null, 
       "Please select only Excel file.",
       "Error",JOptionPane.ERROR_MESSAGE);
    }
    else
    {
     fillData(file);
     model = new DefaultTableModel(data, 
       headers);
     tableWidth = model.getColumnCount() 
       * 150;
     tableHeight = model.getRowCount() 
       * 25;
     table.setPreferredSize(new Dimension(
       tableWidth, tableHeight));
 
     table.setModel(model);
    }
   }
  });

  table = new JTable();
  table.setAutoCreateRowSorter(true);
  model = new DefaultTableModel(data, headers);

  table.setModel(model);
  table.setBackground(Color.pink);

  table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
  table.setEnabled(false);
  table.setRowHeight(25);
  table.setRowMargin(4);

  tableWidth = model.getColumnCount() * 150;
  tableHeight = model.getRowCount() * 25;
  table.setPreferredSize(new Dimension(
    tableWidth, tableHeight));

  scroll = new JScrollPane(table);
  scroll.setBackground(Color.pink);
  scroll.setPreferredSize(new Dimension(300, 300));
  scroll.setHorizontalScrollBarPolicy(
    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
  scroll.setVerticalScrollBarPolicy(
    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
  getContentPane().add(buttonPanel, 
    BorderLayout.NORTH);
  getContentPane().add(scroll, 
    BorderLayout.CENTER);
  setSize(600, 600);
  setResizable(true);
  setVisible(true);
 }

 /**
  * Fill JTable with Excel file data.
  * 
  * @param file
  * file :contains xls file to display in jTable
  */
 void fillData(File file) {

  Workbook workbook = null;
  try {
   try {
    workbook = Workbook.getWorkbook(file);
   } catch (IOException ex) {
    Logger.getLogger(
      excelTojTable.class.
      getName()).log(Level.SEVERE, 
        null, ex);
   }
   Sheet sheet = workbook.getSheet(0);
   
   headers.clear();
   for (int i = 0; i < sheet.getColumns(); i++) {
    Cell cell1 = sheet.getCell(i, 0);
    headers.add(cell1.getContents());
   }

   data.clear();
   for (int j = 1; j < sheet.getRows(); j++) {
    Vector d = new Vector();
    for (int i = 0; i < sheet.getColumns(); i++) {

     Cell cell = sheet.getCell(i, j);
     
     d.add(cell.getContents());

    }
    d.add("\n");
    data.add(d);
   }
  } catch (BiffException e) {
   e.printStackTrace();
  }
 }

 public static void main(String[] args) {

  new excelTojTable();
 }
}

--------------------------------------------------------------------

So I hope this code is helpful in understanding Of Import Excel Data in JTable.

Feel free to ask me if you have any dought regarding this.
You can also give me suggessions to improve this tutorial.

Leave comments if you like this post...!

Thank you.
Nirav Raval

----------------------------------------------------------------------------------
Follow Other Java Swing Tricks....