Showing posts with label j2me sample. Show all posts
Showing posts with label j2me sample. Show all posts

Splitting String/Text In J2ME

To split string/text in J2ME you can use these methods.
Include one of these method in your applications

public static String[] split (String a,String delimeter){
String c[]=new String[0];
String b=a;
while (true){
int i=b.indexOf(delimeter);
String d=b;
if (i>=0)
d=b.substring(0,i);
String e[]=new String[c.length+1];
for (int k=0;k
e[k]=c[k];
e[e.length-1]=d;
c=e;
b=b.substring(i+delimeter.length(),b.length());
if (b.length()<=0 || i<0 )
break;
} return c;
}
-----
/**
* A method for splitting a string in J2ME.
*
* @param splitStr The string to split.
* @param delimiter The characters to use as delimiters.
* @return An array of strings.
*/
public static String[] Split(String splitStr, String delimiter) {

StringBuffer token = new StringBuffer();
Vector tokens = new Vector();

// split
char[] chars = splitStr.toCharArray();
for (int i=0; i < chars.length; i++) {
if (delimiter.indexOf(chars[i]) != -1) {
// we bumbed into a delimiter
if (token.length() > 0) {
tokens.addElement(token.toString());
token.setLength(0);
}
} else {
token.append(chars[i]);
}
}
// don't forget the "tail"...
if (token.length() > 0) {
tokens.addElement(token.toString());
}

// convert the vector into an array
String[] splitArray = new String[tokens.size()];
for (int i=0; i < splitArray.length; i++) {
splitArray[i] = tokens.elementAt(i);
}
return splitArray;
}

J2ME Encryption with Bouncy Castle

import org.bouncycastle.crypto.*;
import org.bouncycastle.crypto.engines.*;
import org.bouncycastle.crypto.modes.*;
import org.bouncycastle.crypto.params.*;


public class Encryptor {

private BufferedBlockCipher cipher;
private KeyParameter key;

// inisialisasi engine kriptografi.
// array key paling sedikit 8 bytes.
public Encryptor( byte[] key ){
cipher = new PaddedBlockCipher(new CBCBlockCipher(new DESEngine() ) );
this.key = new KeyParameter( key );
}

// inisialisasi engine kriptografi.
// string paling sedikit 8 chars.
public Encryptor( String key ){
this( key.getBytes() );
}

private byte[] callCipher( byte[] data ) throws CryptoException {
int size = cipher.getOutputSize( data.length );
byte[] result = new byte[ size ];
int olen = cipher.processBytes( data, 0, data.length, result, 0 );
olen += cipher.doFinal( result, olen );
if( olen <>
byte[] tmp = new byte[ olen ];
System.arraycopy( result, 0, tmp, 0, olen );
result = tmp;
}
return result;
}

// enkripsi arbitrary byte array
// mengembalikan data terenkripsi dalam bentuk yang berbeda
public synchronized byte[] encrypt( byte[] data ) throws CryptoException {
if( data == null || data.length == 0 ){
return new byte[0];
}

cipher.init( true, key );
return callCipher( data );
}

// enkripsi string.
public byte[] encryptString( String data ) throws CryptoException {

if( data == null || data.length() == 0 ){
return new byte[0];
}
return encrypt( data.getBytes() );
}

// Dekrip arbitrary data.
public synchronized byte[] decrypt( byte[] data )
throws CryptoException {
if( data == null || data.length == 0 ){
return new byte[0];
}

cipher.init( false, key );
return callCipher( data );
}

// Dekrip string
public String decryptString( byte[] data )
throws CryptoException {

if( data == null || data.length == 0 ){

return "";

}
return new String( decrypt( data ) );
}
}

View PNG Image with Thread

/*--------------------------------------------------

* ViewPngThread.java

*

* Download and view a png file. The download is

* done in the background with a separate thread

*

* Example from the book: Core J2ME Technology

* Copyright John W. Muchow http://www.CoreJ2ME.com

* You may use/modify for any non-commercial purpose

*-------------------------------------------------*/

import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

import javax.microedition.io.*;

import java.io.*;


public class ViewPngThread extends MIDlet implements CommandListener

{

private Display display;

private TextBox tbMain;

private Alert alStatus;

private Form fmViewPng;

private Command cmExit;

private Command cmView;

private Command cmBack;

private static final int ALERT_DISPLAY_TIME = 3000;

Image im = null;

public ViewPngThread()

{

display = Display.getDisplay(this);

// Create the Main textbox with a maximum of 75 characters

tbMain = new TextBox("Enter url", "http://www.corej2me.com/midpbook_v1e1/ch14/bird.png", 75, 0);

// Create commands and add to textbox

cmExit = new Command("Exit", Command.EXIT, 1);

cmView = new Command("View", Command.SCREEN, 2);

tbMain.addCommand(cmExit);

tbMain.addCommand(cmView );

// Set up a listener for textbox

tbMain.setCommandListener(this);

// Create the form that will hold the png image

fmViewPng = new Form("");

// Create commands and add to form

cmBack = new Command("Back", Command.BACK, 1);

fmViewPng.addCommand(cmBack);

// Set up a listener for form

fmViewPng.setCommandListener(this);

}

public void startApp()

{

display.setCurrent(tbMain);

}

public void pauseApp()

{ }

public void destroyApp(boolean unconditional)

{ }

/*--------------------------------------------------

* Process events

*-------------------------------------------------*/

public void commandAction(Command c, Displayable s)

{

// If the Command button pressed was "Exit"

if (c == cmExit)

{

destroyApp(false);

notifyDestroyed();

}

else if (c == cmView)

{

// Show alert indicating we are starting a download.

// This alert is NOT modal, it appears for

// approximately 3 seconds (see ALERT_DISPLAY_TIME)

showAlert("Downloading", false, tbMain);

// Create an instance of the class that will

// download the file in a separate thread

Download dl = new Download(tbMain.getString(), this);

// Start the thread/download

dl.start();

}

else if (c == cmBack)

{

display.setCurrent(tbMain);

}

}

/*--------------------------------------------------

* Called by the thread after attempting to download

* an image. If the parameter is 'true' the download

* was successful, and the image is shown on a form.

* If parameter is 'false' the download failed, and

* the user is returned to the textbox.

*

* In either case, show an alert indicating the

* the result of the download.

*-------------------------------------------------*/

public void showImage(boolean flag)

{

// Download failed...

if (flag == false)

{

// Alert followed by the main textbox

showAlert("Download Failure", true, tbMain);

}

else // Successful download...

{

ImageItem ii = new ImageItem(null, im, ImageItem.LAYOUT_DEFAULT, null);

// If there is already an image, set (replace) it

if (fmViewPng.size() != 0)

fmViewPng.set(0, ii);

else // Append the image to the empty form

fmViewPng.append(ii);

// Alert followed by the form holding the image

showAlert("Download Successful", true, fmViewPng);

}

}

/*--------------------------------------------------

* Show an alert with the parameters determining

* the type (modal or not) and the displayable to

* show after the alert is dismissed

*-------------------------------------------------*/

public void showAlert(String msg, boolean modal, Displayable displayable)

{

// Create alert, add text, associate a sound

alStatus = new Alert("Status", msg, null, AlertType.INFO);

// Set the alert type

if (modal)

alStatus.setTimeout(Alert.FOREVER);

else

alStatus.setTimeout(ALERT_DISPLAY_TIME);

// Show the alert, followed by the displayable

display.setCurrent(alStatus, displayable);

}

}

/*--------------------------------------------------

* Class - Download

*

* Download an image file in a separate thread

*-------------------------------------------------*/

class Download implements Runnable

{

private String url;

private ViewPngThread MIDlet;

private boolean downloadSuccess = false;

public Download(String url, ViewPngThread MIDlet)

{

this.url = url;

this.MIDlet = MIDlet;

}

/*--------------------------------------------------

* Download the image

*-------------------------------------------------*/

public void run()

{

try

{

getImage(url);

}

catch (Exception e)

{

System.err.println("Msg: " + e.toString());

}

}

/*--------------------------------------------------

* Create and start the new thread

*-------------------------------------------------*/

public void start()

{

Thread thread = new Thread(this);

try

{

thread.start();

}

catch (Exception e)

{

}

}

/*--------------------------------------------------

* Open connection and download png into a byte array.

*-------------------------------------------------*/

private void getImage(String url) throws IOException

{

ContentConnection connection = (ContentConnection) Connector.open(url);

// * There is a bug in MIDP 1.0.3 in which read() sometimes returns

// an invalid length. To work around this, I have changed the

// stream to DataInputStream and called readFully() instead of read()

// InputStream iStrm = connection.openInputStream();

DataInputStream iStrm = connection.openDataInputStream();

ByteArrayOutputStream bStrm = null;

Image im = null;

try

{

// ContentConnection includes a length method

byte imageData[];

int length = (int) connection.getLength();

if (length != -1)

{

imageData = new byte[length];

// Read the png into an array

// iStrm.read(imageData);

iStrm.readFully(imageData);

}

else // Length not available...

{

bStrm = new ByteArrayOutputStream();

int ch;

while ((ch = iStrm.read()) != -1)

bStrm.write(ch);

imageData = bStrm.toByteArray();

}

// Create the image from the byte array

im = Image.createImage(imageData, 0, imageData.length);

}

finally

{

// Clean up

if (connection != null)

connection.close();

if (iStrm != null)

iStrm.close();

if (bStrm != null)

bStrm.close();

}

// Return to the caller the status of the download

if (im == null)

MIDlet.showImage(false);

else

{

MIDlet.im = im;

MIDlet.showImage(true);

}

}

}

Canvas for processing game actions

/*--------------------------------------------------
* GameActions.java
*
* Canvas for processing game actions
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.com
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class GameActions extends MIDlet
{
private Display display; // The display
private GameActionCanvas canvas; // Canvas

public GameActions()
{
display = Display.getDisplay(this);
canvas = new GameActionCanvas(this);
}

protected void startApp()
{
display.setCurrent( canvas );
}

protected void pauseApp()
{ }

protected void destroyApp( boolean unconditional )
{ }

public void exitMIDlet()
{
destroyApp(true);
notifyDestroyed();
}
}

/*--------------------------------------------------
* GameActionCanvas.java
*
* Game action event handling
*-------------------------------------------------*/
class GameActionCanvas extends Canvas implements CommandListener
{
private Command cmExit; // Exit midlet
private String keyText = null; // Key code text
private GameActions midlet;

/*--------------------------------------------------
* Constructor
*-------------------------------------------------*/
public GameActionCanvas(GameActions midlet)
{
this.midlet = midlet;

// Create exit command & listen for events
cmExit = new Command("Exit", Command.EXIT, 1);
addCommand(cmExit);
setCommandListener(this);
}

/*--------------------------------------------------
* Paint the text representing the key code
*-------------------------------------------------*/
protected void paint(Graphics g)
{
// Clear the background (to white)
g.setColor(255, 255, 255);
g.fillRect(0, 0, getWidth(), getHeight());

// Set color and draw text
if (keyText != null)
{
// Draw with black pen
g.setColor(0, 0, 0);
// Center the text
g.drawString(keyText, getWidth()/2, getHeight()/2, Graphics.TOP | Graphics.HCENTER);
}
}

/*--------------------------------------------------
* Command event handling
*-------------------------------------------------*/
public void commandAction(Command c, Displayable d)
{
if (c == cmExit)
midlet.exitMIDlet();
}

/*--------------------------------------------------
* Game action event handling
* A game action will be converted into a key code
* and handed off to this method
*-------------------------------------------------*/
protected void keyPressed(int keyCode)
{
switch (getGameAction(keyCode))
{
// Place logic of each action inside the case
case FIRE:
case UP:
case DOWN:
case LEFT:
case RIGHT:
case GAME_A:
case GAME_B:
case GAME_C:
case GAME_D:
default:
// Print the text of the game action
keyText = getKeyName(keyCode);
}
repaint();
}
}

Display Alert

//jad file (please verify the jar size)
/*
MIDlet-Name: DisplayAlert
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: DisplayAlert.jar
MIDlet-1: DisplayAlert, , DisplayAlert
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100

*/
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class DisplayAlert extends MIDlet implements CommandListener {
private Display display;

private Alert alert;

private Form form = new Form("Throw Exception");

private Command exit = new Command("Exit", Command.SCREEN, 1);

private boolean exitFlag = false;

public DisplayAlert() {
display = Display.getDisplay(this);
form.addCommand(exit);
form.setCommandListener(this);
}

public void startApp() {
display.setCurrent(form);
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) throws MIDletStateChangeException {
if (unconditional == false) {
throw new MIDletStateChangeException();
}
}

public void commandAction(Command command, Displayable displayable) {
if (command == exit) {
try {
if (exitFlag == false) {
alert = new Alert("Busy", "Please try again.", null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, form);
destroyApp(false);
} else {
destroyApp(true);
notifyDestroyed();
}
} catch (Exception exception) {
exitFlag = true;
}
}
}
}

Accessing Commands

/*--------------------------------------------------
* AccessingCommands.java
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.com
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class AccessingCommands extends MIDlet implements CommandListener
{
private Display display; // Reference to Display object
private Form fmMain; // A Form
private Command cmExit; // A Command to exit the MIDlet

public AccessingCommands()
{
display = Display.getDisplay(this);

cmExit = new Command("Exit", Command.EXIT, 1);

fmMain = new Form("Core J2ME");
fmMain.addCommand(cmExit);
fmMain.setCommandListener(this);
}

// Called by application manager to start the MIDlet.
public void startApp()
{
display.setCurrent(fmMain);
}

// A required method
public void pauseApp()
{ }

// A required method
public void destroyApp(boolean unconditional)
{ }

// Check to see if our Exit command was selected
public void commandAction(Command c, Displayable s)
{
if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
}
}

Sample of graphics, commands, and event handling.

/*
* @(#)Sample.java 1.9 01/06/08
* Copyright (c) 1999-2001 Sun Microsystems, Inc. All Rights Reserved.
*/

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;


/*
* A quick sample of graphics, commands, and event handling.
*/
public class SampleCanvasMIDlet extends MIDlet implements CommandListener {
Display display;
Command exitCommand;
Command backCommand;
Command okCommand;
SampleCanvas sample; // Instance of sample canvas

List itemMenu;
List exclusiveList;
List multipleList;
TextBox textbox;
Ticker ticker;
Alert alert;
Form form;
StringItem stringItem;
ImageItem imageItem;
Image image;
TextField textItem;
ChoiceGroup choiceItem;
DateField dateItem;
Gauge gaugeItem;


public SampleCanvasMIDlet() {
display = Display.getDisplay(this);
exitCommand = new Command("Exit", Command.EXIT, 1);
backCommand = new Command("Back", Command.BACK, 2);
okCommand = new Command("OK", Command.OK, 3);

ticker = new Ticker("Select an item to display");
itemMenu = new List(null, Choice.IMPLICIT);
itemMenu.append("Canvas", null);
itemMenu.append("Form", null);
itemMenu.append("Alert", null);
itemMenu.append("TextBox", null);
itemMenu.append("Exclusive List", null);
itemMenu.append("Multiple Choice", null);

itemMenu.setCommandListener(this);
itemMenu.addCommand(exitCommand);
itemMenu.setTicker(ticker);
display.setCurrent(itemMenu);
}

public void startApp () {
}

public void destroyApp (boolean unconditional) {
}

public void pauseApp () {
}

public void commandAction(Command c, Displayable s) {
if (c == backCommand) {
display.setCurrent(itemMenu);
} else if (s == itemMenu) {
if (c == List.SELECT_COMMAND) {
// Handle the item sected to be displayed
int i = itemMenu.getSelectedIndex();
switch (i) {
case 0: // Show Sample canvas
display.setCurrent(getCanvas());
break;
case 1: // Show the form
display.setCurrent(getForm());
break;
case 2: // Show an alert
display.setCurrent(getAlert("Warning",
"This window will dismiss in two seconds."));
break;
case 3: // Show TextBox
display.setCurrent(getTextBox());
break;
case 4: // Show Exclusive list
display.setCurrent(getExclusiveList());
break;
case 5: // Show Multiple List
display.setCurrent(getMultipleList());
break;
}
} else if (c == exitCommand) {
notifyDestroyed();
}
} else if (s == exclusiveList) {
int i = exclusiveList.getSelectedIndex();
String value = exclusiveList.getString(i);
alert = getAlert("Border selected:", value);
display.setCurrent(alert, itemMenu);
} else if (s == multipleList) {
StringBuffer b = new StringBuffer();
for (int i = 0; i <= 2; i++) {
if (multipleList.isSelected(i)) {
b.append(multipleList.getString(i));
b.append("\n");
}
}
alert = getAlert("Colors selected:", b.toString());
display.setCurrent(alert, itemMenu);
} else if (s == textbox) {
String value = textbox.getString();
alert = getAlert("Text Entered:", value);
display.setCurrent(alert, itemMenu);
} else if (s == form) {
alert = getAlert("Image options saved", "");
display.setCurrent(alert, itemMenu);
}
}

SampleCanvas getCanvas() {
if (sample == null) {
sample = new SampleCanvas();
sample.addCommand(backCommand);
sample.setCommandListener(this);
}
return sample;
}

List getExclusiveList() {
if (exclusiveList == null) {
exclusiveList = new List("Border Style", Choice.EXCLUSIVE);
exclusiveList.append("None", null);
exclusiveList.append("Plain", null);
exclusiveList.append("Fancy", null);
exclusiveList.addCommand(backCommand);
exclusiveList.addCommand(okCommand);
exclusiveList.setCommandListener(this);
}
return exclusiveList;
}

List getMultipleList() {
if (multipleList == null) {
multipleList = new List("Colors to mix", Choice.MULTIPLE);
multipleList.append("Red", null);
multipleList.append("Green", null);
multipleList.append("Blue", null);
multipleList.addCommand(backCommand);
multipleList.addCommand(okCommand);
multipleList.setCommandListener(this);
}
return multipleList;
}

TextBox getTextBox() {
if (textbox == null) {
textbox = new TextBox("Enter a phone number","", 40,
TextField.PHONENUMBER);
textbox.addCommand(backCommand);
textbox.addCommand(okCommand);
textbox.setCommandListener(this);
}
return textbox;
}

Alert getAlert(String title, String contents) {
if (alert == null) {
alert = new Alert(title);
alert.setType(AlertType.WARNING);
alert.setTimeout(2000);
alert.setString(contents);
} else {
alert.setTitle(title);
alert.setString(contents);
}
return alert;
}

Form getForm() {
if (form == null) {
form = new Form("Options");

try {
image = Image.createImage("/images/PhotoAlbum.png");
imageItem = new ImageItem("Preview:", image,
ImageItem.LAYOUT_NEWLINE_BEFORE, "Mountain");
form.append(imageItem);
} catch (java.io.IOException ex) {
}

textItem = new TextField("Title:", "Mountain", 32,
TextField.ANY);
form.append(textItem);

dateItem = new DateField("Date:", DateField.DATE);
dateItem.setDate(new java.util.Date());
form.append(dateItem);

choiceItem = new ChoiceGroup("Size:", Choice.EXCLUSIVE);
choiceItem.append("Small", null);
choiceItem.append("Large", null);
form.append(choiceItem);

gaugeItem = new Gauge("Speed:", true, 10, 5);
form.append(gaugeItem);

form.addCommand(backCommand);
form.addCommand(okCommand);
form.setCommandListener(this);
}
return form;
}
}


class SampleCanvas extends Canvas {
int x, y; // Location of cross hairs
String event = ""; // Last key event type
int keyCode; // Last keyCode pressed
Font font; // Font used for drawing text
int fh; // height of the font
int w, h; // width and height of the canvas
int titleHeight; // Height of the title
int pieSize; // Size of the Pie chart used for width and height
int barSize; // Size of the Bar chart used for width and height
int eventHeight; // Size of the event region
int pad; // Padding used between items

SampleCanvas() {
w = getWidth();
h = getHeight();
font = Font.getFont(Font.FACE_SYSTEM,
Font.STYLE_PLAIN, Font.SIZE_SMALL);
fh = font.getHeight();

/* Compute the sizes of the bar and pie charts
* It should use all the space except for the title
* and event regions.
* Don't let the charts get too small
*/
pad = 2;
titleHeight = fh + pad * 2;
eventHeight = fh * 3;
barSize = h - (titleHeight + pad) - (eventHeight + pad);
if (barSize < 20) // Don't let them get too small
barSize = 20;
if (barSize > (w - pad) / 2) // Shrink to 1/2 width
barSize = (w - pad) / 2;
pieSize = barSize;
}

protected void keyPressed(int key) {
keyCode = key;
event = "Pressed";
handleActions(key);
repaint();
}

protected void keyRepeated(int key) {
keyCode = key;
event = "Repeated";
handleActions(key);
repaint();
}

protected void keyReleased(int key) {
keyCode = key;
event = "Released";
repaint();
}

protected void pointerPressed(int x, int y) {
this.x = x;
this.y = y;
keyCode = 0;
event = "Pressed";
repaint();
}
protected void pointerReleased(int x, int y) {
this.x = x;
this.y = y;
keyCode = 0;
event = "Released";
repaint();
}

protected void pointerDragged(int x, int y) {
this.x = x;
this.y = y;
keyCode = 0;
event = "Dragged";
}

void handleActions(int keyCode) {
int action = getGameAction(keyCode);
switch (action) {
case LEFT:
x -= 1;
break;
case RIGHT:
x += 1;
break;
case UP:
y -= 1;
break;
case DOWN:
y += 1;
break;
}
}

protected void paint(Graphics g) {

g.setFont(font);
g.setGrayScale(255);
g.fillRect(0, 0, w, h);

x = (x < 0) ? w - 1 : x;
y = (y < 0) ? h - 1 : y;
x = x % w;
y = y % h;

// Draw Fill and outline for background of title Text
int swidth = pad * 2 + font.stringWidth("Pie and Bar Samples");
int title_x = (w - swidth)/2;

g.setGrayScale(128);
g.fillRoundRect(title_x, 0, swidth, fh, 5, 5);
g.setGrayScale(0);
g.drawRoundRect(title_x, 0, swidth, fh, 5, 5);

// Sample Text
g.setColor(0, 0, 0);
g.drawString("Pie and Bar Samples",
title_x + pad, pad, Graphics.TOP|Graphics.LEFT);

// Translate to below title text
g.translate(0, titleHeight + pad);

/*
* Draw pie chart on the left side
* using the barSize for width and height
*/
g.setColor(255, 0, 0);
g.fillArc(0, 0, pieSize, pieSize, 45, 270);
g.setColor(0, 255, 0);
g.fillArc(0, 0, pieSize, pieSize, 0, 45);
g.setColor(0, 0, 255);
g.fillArc(0, 0, pieSize, pieSize, 0, -45);
g.setColor(0);
g.drawArc(0, 0, pieSize, pieSize, 0, 360);

// Draw Bar chart on right side of the display
// scale the values to the pieSize maximum value
int yorig = barSize;
int h1 = barSize / 3, h2 = barSize / 2, h3 = barSize;
int avg = (h1 + h2 + h3) / 3;

// Move over to draw Bar chart
g.translate((w + pad) / 2, 0);

int bw = pieSize / 7;
if (bw < 2)
bw = 2;
g.setColor(255, 0, 0);
g.fillRect(bw*1, yorig-h1, bw+1, h1);
g.setColor(0, 255, 0);
g.fillRect(bw*3, yorig-h2, bw+1, h2);
g.setColor(0, 0, 255);
g.fillRect(bw*5, yorig-h3, bw+1, h3);
g.setColor(0);
g.drawRect(bw*1, yorig-h1, bw, h1);
g.drawRect(bw*3, yorig-h2, bw, h2);
g.drawRect(bw*5, yorig-h3, bw, h3);

// Draw axis for bar chart.
g.setGrayScale(0);
g.drawLine(0, 0, 0, yorig);
g.drawLine(0, yorig, barSize, yorig);
g.setStrokeStyle(Graphics.DOTTED);
g.drawLine(0, yorig - avg, barSize, yorig-avg);
g.setStrokeStyle(Graphics.SOLID);

// Restore to left and move down
g.translate(-(w + pad) / 2, pieSize + pad);

// Draw the key and pointer status
g.setColor(128, 128, 128);
int col1 = font.stringWidth("Action:");
g.drawString("Key: ", col1, 0,
Graphics.TOP|Graphics.RIGHT);
g.drawString(keyString(keyCode), col1, 0,
Graphics.TOP|Graphics.LEFT);
g.drawString("Action:", col1, fh,
Graphics.TOP|Graphics.RIGHT);
g.drawString(actionString(keyCode), col1, fh,
Graphics.TOP|Graphics.LEFT);
g.drawString("Event:", col1, fh*2,
Graphics.TOP|Graphics.RIGHT);
g.drawString(event, col1, fh*2,
Graphics.TOP|Graphics.LEFT);
int col2 = 80;
g.drawString("x:", col2, 0,
Graphics.TOP|Graphics.RIGHT);
g.drawString(Integer.toString(x), col2, 0,
Graphics.TOP|Graphics.LEFT);
g.drawString("y:", col2, fh,
Graphics.TOP|Graphics.RIGHT);
g.drawString(Integer.toString(y), col2, fh,
Graphics.TOP|Graphics.LEFT);

// Restore the origin and draw the crosshairs on top
g.translate(-g.getTranslateX(), -g.getTranslateY());

g.setColor(0, 0, 0);
g.drawLine(x, y - 5, x, y + 5);
g.drawLine(x - 5, y, x + 5, y);
}

String keyString(int keyCode) {
if (keyCode == 0) {
return "";
}
return Integer.toString(keyCode);
}

String actionString(int keyCode) {
if (keyCode == 0) {
return "";
}

int action = getGameAction(keyCode);
switch (action) {
case FIRE:
return "Fire";
case LEFT:
return "Left";
case RIGHT:
return "Right";
case DOWN:
return "Down";
case UP:
return "Up";
case GAME_A:
return "Game A";
case GAME_B:
return "Game B";
case GAME_C:
return "Game C";
case GAME_D:
return "Game D";
case 0:
return "";
default:
return Integer.toString(action);
}
}
}

Thread Example in J2ME

/*
J2ME: The Complete Reference

James Keogh

Publisher: McGraw-Hill

ISBN 0072227109

*/
// jad file (Please verify the jar size first)
/*
MIDlet-Name: BackgroundProcessing
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: BackgroundProcessing.jar
MIDlet-1: BackgroundProcessing, , BackgroundProcessing
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100

*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;

public class BackgroundProcessing extends MIDlet
implements CommandListener
{
private Display display;
private Form form;
private Command exit;
private Command start;
public BackgroundProcessing()
{
display = Display.getDisplay(this);
form = new Form("Background Processing");
exit = new Command("Exit", Command.EXIT, 1);
start = new Command("Start", Command.SCREEN, 2);
form.addCommand(exit);
form.addCommand(start );
form.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
destroyApp(false);
notifyDestroyed();
}
else if (command == start)
{
Process process = new Process(this);
process.start();
//Do foreground processing here
}
}
}
class Process implements Runnable
{
private BackgroundProcessing MIDlet;
public Process(BackgroundProcessing MIDlet)
{
this.MIDlet = MIDlet;
}
public void run()
{
try
{
transmit ();
}
catch (Exception error)
{
System.err.println(error.toString());
}
}
public void start()
{
Thread thread = new Thread(this);
try
{
thread.start();
}
catch (Exception error)
{
}
}
private void transmit() throws IOException
{
//Place code here to receive or send transmission.
}
}

Storing Image into RMS

import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.*;
import java.io.*;

public class ImageStore extends MIDlet implements CommandListener {

private Command CmdExit;
private Command CmdOpen;
private Command CmdBack;
private Command CmdSave;
private Display display;
RecordStore rStore;
Form form = null;
Image image = null;
InputStream is =null;

public ImageStore() {

rStore = null;

display = Display.getDisplay(this);

CmdExit = new Command("Exit", 1, 2);
CmdOpen = new Command("Show", 1, 3);
CmdBack = new Command("Back", 1, 3);
CmdSave = new Command("Save", 1, 3);

form = new Form("Image Show");

}

public void startApp() {
try {
rStore = RecordStore.openRecordStore("imagefile", true);
} catch(RecordStoreException recordstoreexception) {
recordstoreexception.printStackTrace();
}
try {

is = getClass().getResourceAsStream("/leaf.jpg");
image = Image.createImage(is);
form.append(image);

} catch(IOException ioexception) { }
form.addCommand(CmdExit);
form.addCommand(CmdSave);
form.addCommand(CmdOpen);
form.setCommandListener(this);
display.setCurrent(form);
}

public void pauseApp() {
}

public void Close() {
try {
rStore.closeRecordStore();
} catch(RecordStoreNotOpenException recordstorenotopenexception) {
recordstorenotopenexception.printStackTrace();
} catch(RecordStoreException recordstoreexception) {
recordstoreexception.printStackTrace();
}
}

public void destroyApp(boolean flag) {
Close();
}

public Image load(int width,int height) {

byte[] b = null;
String imagename = null;
Image image = null;

try {

int i = rStore.getNumRecords();

for(int j = 1; j < i + 1; j++) {

if(rStore.getRecord(j) != null) {

b = rStore.getRecord(j);
ByteArrayInputStream bin =
new ByteArrayInputStream( b );

DataInputStream din = new DataInputStream( bin );

imagename = din.readUTF();
int remaining =
(b.length-imagename.getBytes().length-2)/4;

int[] rawdata = new int[remaining];

for(int k =0 ;k < rawdata.length ;k++) {
rawdata[k] = din.readInt();
}

image = Image.createRGBImage(rawdata,
width, height, false);

bin.reset();
din.close();
din =null;
}
}
} catch (IOException e) {

e.printStackTrace();

} catch(RecordStoreException recordstoreexception) {

recordstoreexception.printStackTrace();

}

return image;
}

public boolean save(Image img, int width,
int height, String imgName) {

if (img == null || width < 0 || height < 0 || imgName == null) {

throw new IllegalArgumentException("Check arguments");

}

int[] imgRgbData = new int[width * height];

try {

img.getRGB(imgRgbData, 0, width, 0, 0, width, height);

} catch (Exception e) {
// Problem getting image RGB data
return false;
}
try {
// Write image data to output stream (in order to get
// the record bytes in needed form)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeUTF(imgName);

for (int i = 0; i < imgRgbData.length; i++) {
dos.writeInt(imgRgbData[i]);
}

// Open record store, create if it doesn't exist
rStore.addRecord(baos.toByteArray(), 0,
baos.toByteArray().length); // Add record

} catch (RecordStoreNotFoundException rsnfe) {
// Record storage not found
return false;
} catch (RecordStoreException rse) {
// Other record storage problem
return false;
} catch (IOException ioe) {
// Problem writing data
return false;
}

return true; // We've successfuly done
}

public void commandAction(Command command, Displayable displayable) {

if(command == CmdExit) {

destroyApp(true);
notifyDestroyed();

}
else if(command == CmdOpen) {

Form showform = new Form("Image from DB");
Image i = load(image.getWidth(),image.getHeight());

if(i !=null ) {

Image img = Image.createImage(i);
showform.append(img);

}

showform.addCommand(CmdBack);
showform.setCommandListener(this);
display.setCurrent(showform);

} else if(command == CmdBack) {

display.setCurrent(form);

} else if(command == CmdSave) {

byte[] b = null;
Alert a =new Alert("Image saved");

try {
if(save(image,image.getWidth(),image.getHeight(),"leaf"))
a.setString("Success");
else
a.setString("Failed");
a.setTimeout(1000);
} catch (Exception e) {
e.printStackTrace();
}
display.setCurrent(a);
}
}
}

Animation Midlet

/*
J2ME in a Nutshell
By Kim Topley
ISBN: 0-596-00253-X

*/


import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemStateListener;
import javax.microedition.midlet.MIDlet;

public class AnimationMIDlet extends MIDlet
implements CommandListener, ItemStateListener {

// The MIDlet's Display object
private Display display;

// Flag indicating first call of startApp
protected boolean started;

// Exit command
private Command exitCommand;

// Setup command
private Command setupCommand;

// Run command
private Command runCommand;

// Configuration form
private Form form;

// Animation canvas
private AnimationCanvas canvas;

// Gauge for block count
private Gauge blockGauge;

// Gauge for frame rate
private Gauge rateGauge;

// Initial frame rate
private static final int FRAME_RATE = 1;

// Initial number of blocks
private static final int BLOCK_COUNT = 1;

protected void startApp() {
if (!started) {
display = Display.getDisplay(this);
form = new Form("Animation");
rateGauge = new Gauge("Frame rate", true, 10, FRAME_RATE);
blockGauge = new Gauge("Blocks", true, 4, BLOCK_COUNT);
form.append(rateGauge);
form.append(blockGauge);
form.setItemStateListener(this);

canvas = createAnimationCanvas();

exitCommand = new Command("Exit", Command.EXIT, 0);
setupCommand = new Command("Setup", Command.SCREEN, 0);
runCommand = new Command("Run", Command.SCREEN, 0);

canvas.addCommand(exitCommand);
canvas.addCommand(setupCommand);
form.addCommand(exitCommand);
form.addCommand(runCommand);

form.setCommandListener(this);
canvas.setCommandListener(this);

display.setCurrent(form);
started = true;
}
}

protected void pauseApp() {
}

protected void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
// Exit. No need to call destroyApp
// because it is empty.
notifyDestroyed();
} else if (c == runCommand) {
display.setCurrent(canvas);
} else if (c == setupCommand) {
display.setCurrent(form);
}
}

public void itemStateChanged(Item item) {
if (item == blockGauge) {
int count = blockGauge.getValue();
if (count < 1) {
count = 1;
}
canvas.setBlockCount(count);
} else if (item == rateGauge) {
int count = rateGauge.getValue();
if (count < 1) {
count = 1;
}
canvas.setFrameRate(count);
}
}

// Creates the canvas that will draw the block
protected AnimationCanvas createAnimationCanvas() {
return new AnimationCanvas();
}

class AnimationCanvas extends Canvas {

// Size of each block
protected static final int SIZE = 4;

// Initial speeds in the X direction
protected final int[] xSpeeds = { 2, -2, 0, -2 };

// Initial speeds in the Y direction
protected final int[] ySpeeds = { 2, -2, 2, -0 };

// Background color
protected int background = display.isColor() ? 0 : 0xc0c0c0;

// Foreground color
protected int foreground = display.isColor() ? 0xffff00 : 0;

// Width of screen
protected int width = getWidth();

// Height of screen
protected int height = getHeight();

// The screen update rate
protected int frameRate;

// The blocks to draw on the screen
protected Block[] blocks;

// The update timer
protected Timer timer;

// The update timer task
protected TimerTask updateTask;

// Gets the maximum number of blocks
public int getMaxBlocks() {
return blocks.length;
}

// Constructs a canvas with default settings
AnimationCanvas() {
setBlockCount(BLOCK_COUNT);
setFrameRate(FRAME_RATE);
}

// Sets the number of blocks to draw
public void setBlockCount(int count) {
if (count > xSpeeds.length) {
throw new IllegalArgumentException("Cannot have more than "
+ xSpeeds.length + " blocks");
}

blocks = new Block[count];
createBlocks();
}

// Gets the number of blocks to draw
public int getBlockCount() {
return blocks.length;
}

// Sets the number of updates per second
public void setFrameRate(int frameRate) {
if (frameRate < 1 || frameRate > 10) {
throw new IllegalArgumentException("Frame rate must be > 0 and <= 10");
}
this.frameRate = frameRate;
if (isShown()) {
startFrameTimer();
}
}

// Gets the number of updates per second
public int getFrameRate() {
return frameRate;
}

// Paint canvas background and all
// of the blocks in their correct locations.
protected void paint(Graphics g) {
// Paint with the background color
g.setColor(background);
g.fillRect(0, 0, width, height);

// Draw all of the blocks
g.setColor(foreground);
synchronized (this) {
for (int i = 0, count = blocks.length; i < count; i++) {
g.fillRect(blocks[i].x, blocks[i].y, SIZE, SIZE);
}
}
}

// Notification that the canvas has been made visible
protected void showNotify() {
// Start the frame timer running
startFrameTimer();
}

// Notification that the canvas is no longer visible
protected void hideNotify() {
// Stop the frame timer
stopFrameTimer();
}

// Creates the blocks to be displayed
private void createBlocks() {
int startX = (width - SIZE)/2;
int startY = (height - SIZE)/2;
for (int i = 0, count = blocks.length; i < count; i++) {
blocks[i] = new Block(startX, startY, xSpeeds[i], ySpeeds[i]);
}
}

// Starts the frame redraw timer
protected void startFrameTimer() {
timer = new Timer();

updateTask = new TimerTask() {
public void run() {
moveAllBlocks();
}
};
long interval = 1000/frameRate;
timer.schedule(updateTask, interval, interval);
}

// Stops the frame redraw timer
protected void stopFrameTimer() {
timer.cancel();
}

// Called on expiry of timer.
public synchronized void moveAllBlocks() {
// Update the positions and speeds
// of all of the blocks
for (int i = 0, count = blocks.length; i < count; i++) {
blocks[i].move();

// Request a repaint of the screen
repaint();
}
}

// Inner class used to represent a block on the screen
class Block {
int x; // X position
int y; // Y position
int xSpeed; // Speed in the X direction
int ySpeed; // Speed in the Y direction

Block(int x, int y, int xSpeed, int ySpeed) {
this.x = x;
this.y = y;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
}

void move() {
x += xSpeed;
if (x <= 0 || x + SIZE >= width) {
xSpeed = -xSpeed;
}

y += ySpeed;
if (y <= 0 || y + SIZE >= height) {
ySpeed = -ySpeed;
}
}
}
}
}
 

Design by Blogger Buster | Distributed by Blogging Tips