Wednesday 12 June 2013

Working with Image & Image Button in LWUIT

Working with Images & Image Button in LWUIT:

In this post we will discuss about how to create an Image button and also how to add text in the image button clearly.

We are using LWUIT in our application so If you want to follow this post you should add and initialize your project with LWUIT. Adding LWUIT is not a difficult one We have a clear post stating how to add and initialize LWUIT in our Application Read that post here.


We used the Project name as Image_Sample and Java file named as ImageSample.Java and we used the image down.jpg and download.jpg in this application

First create a new MIDlet project and add LWUIT to your project then add the Java ME MIDlet file to your project.Then you have to add the Image into your resource folder by copy the source image and paste it in your res folder of your project( Image_Sample/res/ in our case)

To create an Image we should use the following code and it should be enclosed in try catch block

try {
 img=Image.createImage("/down.jpg");
 img1=Image.createImage("/download.jpg");
     } catch (IOException e) {
}

Creating Normal Image in LWUIT:

To create a normal Image you should add the Image to the Label component then you can display the Label in the screen

Label l1=new Label(img);

form.addComponent(l1);

Creating ImageButton in LWUIT

To create a image button you should add the Image object to the Button extension so that the code will be like following

Button b=new Button("Button Text",Image_Object);

e.g
b1=new Button("Click me",img);
b1.setTextPosition(Component.BOTTOM);

Here we provided a sample code which used a simple image and Image button in LWUIT Nokia application

Sample Code:

import java.io.IOException;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import com.sun.lwuit.Button;
import com.sun.lwuit.Component;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;

public class ImageSample extends MIDlet {

Form form;
Image img,img1;
Button b1;
public ImageSample() {
// TODO Auto-generated constructor stub
}

protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub

}

protected void pauseApp() {
// TODO Auto-generated method stub

}

protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
Display.init(this);
form=new Form("Image Sample");
try {
img=Image.createImage("/down.jpg");
img1=Image.createImage("/download.jpg");
} catch (IOException e) {
}
   Label l1=new Label(img1);
b1=new Button("Click me",img);
b1.setTextPosition(Component.BOTTOM);
form.addComponent(l1);
form.addComponent(b1);
form.show();
}

}

Your output will resemble the one given below

image button in LWUIT

We used the Images given below for our project
LWUIT
down.jpg

LWUIT
download.jpg



2 comments :