Saturday, October 27, 2012

Add Native Support to JS in Android HTML5 Apps

Running HTML 5 apps in Android , is not effective as you loss a lot of native power , Android provides the ability to expose native power to JS so you can use the powerful native support in your app.

Here is the simple steps:


1. Create any class and name it any thing like JavaScriptInterface
Example:


public class JavaScriptInterface {
        Context mContext;

        JavaScriptInterface(Context c) {
            mContext = c;
        }

        public void doSomething() {
         System.err.println("inside do something");
        }
}

2. The class should have constructor that take Context as parameter

3. During instatiation send the activity object in the constructor and add nick(prefix) name to be used inside JS to call this class methods:

     webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");


Example:

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_crazy);
    WebView webView=(WebView)findViewById(R.id.webView);
    webView.setWebChromeClient(new WebChromeClient());
    webView.getSettings().setJavaScriptEnabled(true); 
    webView.getSettings().setDatabaseEnabled(true);
    webView.getSettings().setDatabasePath("/data/data/osa.ora.test/databases/");
    webView.getSettings().setDomStorageEnabled(true);
    //remove this line for emulator bug in Android 2.3
    webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
       //the following line to prevent the backlight from going during application running.
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    webView.loadUrl("file:///android_asset/www/index.html");    
    }


4. In the JS call this methods

Example:
Android.doSomething();

You can see in the console the outcome of the sys err statement.
(Android is the prefix we have specified during creating instance of this JS interface)

5. Of course we can have many interfaces each for specific purpose.

Simple and straightforward but there is a bug in android emulator in 2.3 so better to test it on mobile devices direct in case you need to test it on such platform.

Monday, October 22, 2012

"Hit The Ball" .. Android Game

I have published 1st version of my game "Hit The Ball" over Android platform.


Links:

Here is the link for the demo version :
https://play.google.com/store/apps/details?id=hit.ball.game.demo

And this is the link to commercial version :
https://play.google.com/store/apps/details?id=hit.ball.game

Description:
The game is based on HTML 5 technology and use Java Script Interface for some native work.
It uses Box2D implementation as physics engine for the game.

The idea behind this game is you play with a ball and you need to hit the other ball in the scene.
If you hit the other ball , you go to next level, where it get complicated little bit.
You can select the destination of the shoot by your click/finger.
If you didn't shoot the ball , the ball will be automatically shoot to a default location.
If you pick small ball you get extra trial.
Pay attention to the speed bar during shooting.
You can resume the game from the last successful level which is auto-saved.

Game screen shots:




Saturday, October 6, 2012

Java Fork Join & Parallel Programming

After emerging of multi-cores programs , a major shift to the application development to utilize these cores by forking many threads/process for the applications esp. in the intensive processing procedure.

Java came lately to the paradigm shift with concurrency APIs in Java 7  (JSR 166) (which was initially planned in Java 5), the framework will go under another improvement to facilitate the current complex way in Java 8.

Best fit algorithms for paralization is divide-and-conquer algorithms.
In this post we will go through example of using the fork-join to develop quick sort enhancement..

1) Framework important parts:
-ForkJoinTask : this is a task to be forked and joined after processing.
It has lifecycle methods as doJoin , doInvoke , doExecute plus status.

- RecursiveAction extends ForkJoinTask: represent a recursive action..
It has important method which is compute..
We will extend this class and override compute method to do what we need.

-ForkJoinPool : represents the pool for fork and join framework , you can initialize it by the number of cores or by fixed magic number ...
Note: To get the number of processors/cores:
int processors = Runtime.getRuntime().availableProcessors();

2) Non-parallel Quick sort:
Static method that process the numbers[] to sort them...


//non-parallellll...
private static int[] numbers;
private static void quicksort(int low, int high) {
int i = low, j = high;
// Get the pivot element from the middle of the list
int pivot = numbers[low + (high-low)/2];

// Divide into two lists
while (i <= j) {
// If the current value from the left list is smaller then the pivot
// element then get the next element from the left list
while (numbers[i] < pivot) {
i++;
}
// If the current value from the right list is larger then the pivot
// element then get the next element from the right list
while (numbers[j] > pivot) {
j--;
}

// If we have found a values in the left list which is larger then
// the pivot element and if we have found a value in the right list
// which is smaller then the pivot element then we exchange the
// values.
// As we are done we can increase i and j
if (i <= j) {
exchange(i, j);
i++;
j--;
}
}
// Recursion
if (low < j)
quicksort(low, j);
if (i < high)
quicksort(i, high);
}

private static void exchange(int i, int j) {
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}



3) Using Fork-Join:


public class ParallelQuickSort extends RecursiveAction {
    Phaser phaser;
    int[] arr = null;
    int left;
    int right;

    ParallelQuickSort(Phaser phaser, int[] arr) {
        this(phaser, arr, 0, arr.length - 1);
    }

    ParallelQuickSort(Phaser phaser, int[] arr, int left, int right) {
        this.phaser = phaser;
        this.arr = arr;
        this.left = left;
        this.right = right;
        phaser.register();  //important
    }


    private ParallelQuickSort leftSorter(int pivotI) {
        return new ParallelQuickSort(phaser, arr, left, --pivotI);
    }

    private ParallelQuickSort rightSorter(int pivotI) {
        return new ParallelQuickSort(phaser, arr, pivotI, right);
    }

    private void recurSort(int leftI, int rightI) {
        if (rightI - leftI > 7) {
            int pIdx = partition(leftI, rightI, getPivot(arr, leftI, rightI));
            recurSort(leftI, pIdx - 1);
            recurSort(pIdx, rightI);
        } else if (rightI - leftI > 0) {
            insertionSort(leftI, rightI);
        }
    }


    @Override
    protected void compute() {
        if (right - left > 1000) {   // if more than 1000 (totally arbitrary number i chose) try doing it parallelly
            int pIdx = partition(left, right, getPivot(arr, left, right));
            leftSorter(pIdx).fork();
            rightSorter(pIdx).fork();

        } else if (right - left > 7) {  // less than 1000 sort recursively in this thread
            recurSort(left, right);

        } else if (right - left > 0) {  //if less than 7 try simple insertion sort
            insertionSort(left, right);
        }

        if (isRoot()) { //if this instance is the root one (the one that started the sort process), wait for others
                        // to complete.
            phaser.arriveAndAwaitAdvance();
        } else {  // all not root one just arrive and de register not waiting for others.
            phaser.arriveAndDeregister();
        }
    }

    /** Patition the array segment based on the pivot   **/
    private int partition(int startI, int endI, int pivot) {
        for (int si = startI - 1, ei = endI + 1; ; ) {
            for (; arr[++si] < pivot;) ;
            for (; ei > startI && arr[--ei] > pivot ; ) ;
            if (si >= ei) {
                return si;
            }
            swap(si, ei);
        }
    }

    private void insertionSort(int leftI, int rightI) {
        for (int i = leftI; i < rightI + 1; i++)
            for (int j = i; j > leftI && arr[j - 1] > arr[j]; j--)
                swap(j, j - 1);

    }

    private void swap(int startI, int endI) {
        int temp = arr[startI];
        arr[startI] = arr[endI];
        arr[endI] = temp;
    }

    /**
     * Check to see if this instance is the root, i.e the first one used to sort the array.
     * @return
     */
    private boolean isRoot() {
        return arr.length == (right - left) + 1;
    }

    /**
     * copied from java.util.Arrays
     */
    private int getPivot(int[] arr, int startI, int endI) {
        int len = (endI - startI) + 1;
        // Choose a partition element, v
        int m = startI + (len >> 1);       // Small arrays, middle element
        if (len > 7) {
            int l = startI;
            int n = startI + len - 1;
            if (len > 40) {        // Big arrays, pseudomedian of 9
                int s = len / 8;
                l = med3(arr, l, l + s, l + 2 * s);
                m = med3(arr, m - s, m, m + s);
                n = med3(arr, n - 2 * s, n - s, n);
            }
            m = med3(arr, l, m, n); // Mid-size, med of 3
        }
        int v = arr[m];
        return v;
    }

    /**
     * copied from java.util.Arrays
     */
    private static int med3(int x[], int a, int b, int c) {
        return (x[a] < x[b] ?
                (x[b] < x[c] ? b : x[a] < x[c] ? c : a) :
                (x[b] > x[c] ? b : x[a] > x[c] ? c : a));
    }


4) Testing :
Generate big random array then sort it using both and see the results:

       private static int[] getRandom(int i) {
        Random randomGenerator = new Random(i);
        int[] array = new int[i];
        for (int n = 0; n < i; n++) {
            array[n] = randomGenerator.nextInt();
        }
        return array;
    }

    public static void main(String[] args) throws InterruptedException {
        int[] arr = getRandom(1000000);
        numbers=Arrays.copyOf(arr, arr.length);
        int[] arr2=Arrays.copyOf(arr, arr.length);
        System.out.println("show: " + arr.length+" "+numbers.length);
        System.out.println("show: " + arr[0]+" "+arr[arr.length-1]);
        System.out.println("show: " + numbers[0]+" "+numbers[numbers.length-1]);
        ForkJoinPool pool = new ForkJoinPool();
        StopWatch  stopWatch=new StopWatch();
        Phaser phaser = new Phaser();
        pool.invoke(new ParallelQuickSort(phaser, arr));
        stopWatch.stop();
        System.out.println("Elapsed Time: " + stopWatch.getElapsedTime());
        System.out.println("show: " + arr[0]+" "+arr[arr.length-1]);
        System.out.println("show: " + numbers[0]+" "+numbers[numbers.length-1]);
        numbers=getRandom(1000000);
        stopWatch=new StopWatch();        
        quicksort(0,numbers.length-1);
        stopWatch.stop();
        System.out.println("Elapsed Time: " + stopWatch.getElapsedTime());
        System.out.println("show: " + arr[0]+" "+arr[arr.length-1]);
        System.out.println("show: " + numbers[0]+" "+numbers[numbers.length-1]);     
        stopWatch=new StopWatch();        
        Arrays.sort(arr2);
        stopWatch.stop();
        System.out.println("Elapsed Time: " + stopWatch.getElapsedTime());
    }



5) Output :

Example of output of this code:


show: 1000000 1000000
show: 1608240105 -356486679
show: 1608240105 -356486679
Elapsed Time: 68
show: -2147481329 2147476538
show: 1608240105 -356486679
Elapsed Time: 114
show: -2147481329 2147476538
show: -2147481329 2147476538
Elapsed Time: 92



So sorting 1 million element in the array toke 65 milliseconds using fork-join and 113 milliseconds using single threaded mode, and using java optimized quick sort it takes 92 milliseconds.

Saturday, June 16, 2012

Text To Speech in JSP page (or HTML pages)

In this post we will show how to add text to speech support to your web pages , simplified steps will be followed for that.

We will use eSpeak which is open source project: http://espeak.sourceforge.net/

Link: http://espeak.sourceforge.net/

1) Create Java Web Application : (or HTML page)
2) Create folder JS and place the following files:
- speakWorker.js
- speakGenerator.js
- speakClient.js

3) Edit speakClient.js and change the 3rd line in the file to point to your JS folder :

speakWorker = new Worker('js/speakWorker.js');

4) Create JSP pages (or HTML page) :

a) Add the following JS imports in the header:
 <script src="js/speakGenerator.js"></script>
  <script src="js/speakClient.js"></script>

b) Add this function in the header as well:
  <script>
    function textToSpeech(text){
       // you can change any of these voice characteristics
        speak(text, { amplitude: 100, wordgap: 1, pitch: 50, speed: 175 });
    }
  </script>

c) Add this div to your page body :
  <div id="audio"></div>

5) In your page use the function we have just created like this:
I have added small icon beside each filed to text to speech its content in human friendly way : Name is ..., City is ...., Country is ......


Name : <input type="text" name="name" id="name" size=50 value="Osama Oransa"><img src="images/tts.png" onclick="textToSpeech('Name is '+document.forms[0].name.value); return false" style="cursor:pointer;vertical-align: middle">

The nice thing in this open source project that it support a lot of languages and different voice with ability to tune each voice using many features and if you didn't find your language you can generate the speech generator for it.



Saturday, June 2, 2012

Accessing WebCam within JSP

I keep getting questions about how we can use web camera inside jsp files , in this post i will show you how to use the web cam from within jsp file.


We will use jQuery wrapper of flash plugin for that..
My reference in that is http://www.xarg.org
There is a guide you can follow instead of my post: http://www.xarg.org/project/jquery-webcam-plugin/
Here is the simplified steps:
1.Create resources folder with the following content from the mentioned web site:
jquery.js
jquery-1.js
either : jscam.swf or jscam_canvas_only.swf

2.Create JSP file and put the following code:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<title>Test Web Cam</title>
<style type="text/css">
#webcam, #canvas {
    width: 320px;
    border:20px solid #333;
    background:#eee;
    -webkit-border-radius: 20px;
    -moz-border-radius: 20px;
    border-radius: 20px;
}

#webcam {
    position:relative;
    margin-top:50px;
    margin-bottom:50px;
}

#webcam > span {
    z-index:2;
    position:absolute;
    color:#eee;
    font-size:10px;
    bottom: -16px;
    left:152px;
}

#canvas {    border:20px solid #ccc;
    background:#eee;
}
</style><script type="text/javascript" src="resources/jquery-1.js"></script>
<script type="text/javascript" src="resources/jquery.js"></script>
</head><body>
<p id="status" style="height:22px; color:#c00;font-weight:bold;"></p>
<div id="webcam">
    <span>Your WebCam should be here!</span>
</div>

<p style="width:360px;text-align:center; ">
    <a href="javascript:webcam.capture(3);changeFilter();void(0);">Take a picture after 3 seconds</a> |
    <a href="javascript:webcam.capture();changeFilter();void(0);">Take a picture instantly</a></p>

<script type="text/javascript">
var pos = 0;
var ctx = null;
var cam = null;
var image = null;

var filter_on = false;
var filter_id = 0;

$(function() {

        var pos = 0, ctx = null, saveCB, image = [];
        var canvas = document.createElement("canvas");
        canvas.setAttribute('width', 320);
        canvas.setAttribute('height', 240); 
        if (canvas.toDataURL) {
                ctx = canvas.getContext("2d");             
                image = ctx.getImageData(0, 0, 320, 240);
                saveCB = function(data) {                       
                        var col = data.split(";");
                        var img = image;
                        for(var i = 0; i < 320; i++) {
                                var tmp = parseInt(col[i]);
                                img.data[pos + 0] = (tmp >> 16) & 0xff;
                                img.data[pos + 1] = (tmp >> 8) & 0xff;
                                img.data[pos + 2] = tmp & 0xff;
                                img.data[pos + 3] = 0xff;
                                pos+= 4;
                        }
                        if (pos >= 4 * 320 * 240) {
                                ctx.putImageData(img, 0, 0);
                                $.post("/TestWebCam/UploadServlet", {type: "data", image: canvas.toDataURL("image/png")});
                                pos = 0;
                        }
                };
        } else {
                saveCB = function(data) {
                        image.push(data);                       
                        pos+= 4 * 320;                       
                        if (pos >= 4 * 320 * 240) {
                                $.post("/TestWebCam/UploadServlet", {type: "pixel", image: image.join('|')});
                                pos = 0;
                        }
                };
        }
        $("#webcam").webcam({
                width: 320,
                height: 240,
                mode: "callback",
                swffile: "resources/jscam_canvas_only.swf",
                onSave: saveCB,
                onCapture: function () {
                        webcam.save();
                },
                debug: function (type, string) {
                        console.log(type + ": " + string);
                }
        });

});
</script>
</body>
</html>

3.Create a Servlet named: UploadServlet with the following code:
package osa.ora;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * UploadServlet
 * Author Osama Oransa
 */
public class UploadServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

    private static final long serialVersionUID = 529869125345702992L;
    public UploadServlet() {
        super();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("SAVING>>>>>>>>>>>>>>>>>>>>");
        String type = request.getParameter("type");
        String image = request.getParameter("image");
        System.out.println("SAVING>>>>>>>>>>>>>>>>>>>>Type=" + type);
        System.out.println("SAVING>>>>>>>>>>>>>>>>>>>>data=" + image);
        if (type != null) {
            return;
        }

        String byteStr = image.split(",")[1];
        byte[] bytes = Base64.decode(byteStr);
//Now you have the image bytes ready to save in File/DB/....etc..

//Or use the pixel data for old browser and convert the pixel comma separated values into int[] then call methods similar to the following one:

public static Image getImageFromArray(int[] pixels, int width, int height) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
WritableRaster raster = (WritableRaster) image.getData();
raster.setPixels(0,0,width,height,pixels);
return image;
}
    }
}
           
This will show you the encoded png data ...you can decode it or keep it encoded , save it to DB ...etc...
If you are doing a video chat application you need to capture the images in periodic manner and upload it , you may include the source & destination ids to distribute the chat images correctly..

This code only works with integrated camera in the laptop not with USB external camera.

These are simplified steps so you can copy and paste and let it work easily.
But in case you need more details , you may refer to the original URL for more clarification on how to control it more..

NOTE:
Another alternative is to use the following project:  https://github.com/jhuckaby/webcamjs

Tuesday, April 3, 2012

WebCam Video Capture in Java

I got a lot of requests asking for how to do video capturing in Java as comments on my previous post :

Capture photo / image from Web Cam / USB Camera using Java

In this quick post i will highlight how i did this functionality in Interactive4j

We will use the library LTI-CIVIL which is part of FMJ (Freedom for Media in Java).



PreRequisities:

-Download the library and place it correctly in your classpath and load the native library using JVM parameter exactly as the previous mentioned post above.
Download from here:  https://sourceforge.net/projects/lti-civil/

Steps:

1) Create Interface For Captured Images:
public interface CaptureListener {
/**
* Method called once capturing of the web cam jpg file is done.
* @param filename
*/
public void setCaptureFile(File filename);
}

2) Create A Wrapper Class:
This class wrap the camera functionality..

/**
* JHCaptureUtil class
* Used for capture images through the usb (camera, scanner,...etc)
* Osama Oransa
* Interactive4J
* (c) 2011
**/
package osa.ora.utils;

import com.lti.civil.*;
import com.lti.civil.awt.AWTImageConverter;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import osa.ora.utils.faces.CaptureListener;

/**
*
* @author mabdelmo
*/
public class JHCaptureUtil implements CaptureObserver {

CaptureStream captureStream = null;
CaptureListener captureListener;
String fileName;
/**
* Constructor accept the listener and file to save image into.
* @param captureListener
* @param fileName
*/
public JHCaptureUtil(CaptureListener captureListener, String fileName) {
this.fileName = fileName;
this.captureListener = captureListener;
init();
}
private void init(){
System.out.println("Init....");
/*
* initialize capturing to use the current devices...
*/
CaptureSystemFactory factory = DefaultCaptureSystemFactorySingleton.instance();
CaptureSystem system;
try {
system = factory.createCaptureSystem();
system.init();
List list = system.getCaptureDeviceInfoList();
int i = 0;
if (i < list.size()) {
CaptureDeviceInfo info = (CaptureDeviceInfo) list.get(i);
System.out.println((new StringBuilder()).append("Device ID ").append(i).append(": ").append(info.getDeviceID()).toString());
System.out.println((new StringBuilder()).append("Description ").append(i).append(": ").append(info.getDescription()).toString());
captureStream = system.openCaptureDeviceStream(info.getDeviceID());
captureStream.setObserver(this);
}
} catch (CaptureException ex) {
Logger.getLogger(JHCaptureUtil.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Start capture method
*/
public void start() {
//System.out.println("Start....");
try {
captureStream.start();
} catch (CaptureException ex) {
Logger.getLogger(JHCaptureUtil.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Stop capture method
*/
public void stop() {
//System.out.println("Stop....");
try {
captureStream.stop();
} catch (CaptureException ex) {
Logger.getLogger(JHCaptureUtil.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
*
* @param stream
* @param image
*/
public void onNewImage(CaptureStream stream, Image image) {
//System.out.println("get new image....");
byte bytes[] = null;
try {
if (image == null) {
return;
}
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(os);
jpeg.encode(AWTImageConverter.toBufferedImage(image));
os.close();
bytes = os.toByteArray();
if (bytes == null) {
return;
}
} catch (Throwable t) {
t.printStackTrace();
bytes = null;
return;
}
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
File currentImageFile = new File(fileName);
FileOutputStream fos = new FileOutputStream(currentImageFile);
fos.write(bytes);
fos.close();
captureListener.setCaptureFile(currentImageFile);
} catch (IOException ex) {
Logger.getLogger(JHCaptureUtil.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
*
* @param stream
* @param ce
*/
public void onError(CaptureStream stream, CaptureException ce) {
System.out.println("Error : "+ce.getStackTrace());
}
}




3) Write the code that control your wrapper class:
Here is sample usage code that display a dialog with one image or a video .. You need to add 2 buttons 1 for image capture and 1 for video capture and add the action listeners on these buttons..


int mode=0;
static int ONE_PHOTO=0;
static int MULTI_PHOTO=1;
JHCaptureUtil webCam;

//this method to capture one image

private void captureImageButtonActionPerformed(java.awt.event.ActionEvent evt) {
mode=ONE_PHOTO;
if(webCam==null) webCam=new JHCaptureUtil(this, "/myWebCamPic.jpg");
webCam.start();
}

private void captureVideoActionPerformed(java.awt.event.ActionEvent evt) {
mode=MULTI_PHOTO;
if(webCam==null) webCam=new JHCaptureUtil(this, "/myWebCamPic.jpg");
webCam.start();
}


You class must implements : CaptureListener , this interface has 1 method inside it :
public void setCaptureFile(File filename);

And this is the interface method implementation that display the image without saving the photos (you can change the implementation)


JDialog monitorjDialog;
JLabel monitorLabel;
JScrollPane monitorScroll;

public void setCaptureFile(File filename) {
if(mode==ONE_PHOTO){
System.out.println("No more photos");
JDialog jDialog=new JDialog(this.getFrame(),true);
Image image=ImageUtils.loadJPG(filename.getAbsolutePath());
jDialog.setBounds(this.getFrame().getX()+50,this.getFrame().getY()+50,500, 500);
JLabel label=new JLabel(new ImageIcon(image));
JScrollPane jscroll=new JScrollPane(label);
jDialog.add(jscroll);
jDialog.setVisible(true);
jDialog.validate();
webCam.stop();
}else{
System.out.println("display new photo");
if(monitorjDialog==null) {
monitorjDialog=new JDialog(this.getFrame(),false);
monitorjDialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
webCam.stop();
}
});
Image image=ImageUtils.loadJPG(filename.getAbsolutePath());
monitorjDialog.setBounds(this.getFrame().getX()+50,this.getFrame().getY()+50,image.getWidth(null), image.getHeight(null));
monitorLabel=new JLabel(new ImageIcon(image));
monitorScroll=new JScrollPane(monitorLabel);
monitorjDialog.add(monitorScroll);
monitorjDialog.setVisible(true);
monitorjDialog.validate();
}else{
Image image=ImageUtils.loadJPG(filename.getAbsolutePath());
monitorjDialog.remove(monitorScroll);
monitorScroll.remove(monitorLabel);
monitorLabel=new JLabel(new ImageIcon(image));
monitorScroll=new JScrollPane(monitorLabel);
monitorjDialog.add(monitorScroll);
monitorjDialog.validate();
}
}
}

4) Utility method used: ImageUtils.loadJPG ..
public static Image loadJPG(String filename) {
FileInputStream in = null;
try {
in = new FileInputStream(filename);
} catch (java.io.FileNotFoundException io) {
System.out.println("File Not Found");
}
JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
BufferedImage bi = null;
try {
bi = decoder.decodeAsBufferedImage();
in.close();
} catch (java.io.IOException io) {
System.out.println("IOException");
}
return bi;
}

That's all needed !