Showing posts with label midlet. Show all posts
Showing posts with label midlet. Show all posts

Simple demo of using timers

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

public class TimerMidlet extends MIDlet implements CommandListener
{
private Display display;
private Form form;
private Command exit;
private Command stop;
private Timer timer;
private RunTimerTask tt;
private int count = 0;

public timerMidlet()
{
form = new Form("Timer");
exit = new Command("Exit", Command.EXIT, 1);
stop= new Command("Stop", Command.STOP, 2);
}

public void startApp ()
{
display = Display.getDisplay(this);
form.addCommand(exit);
form.addCommand(stop);
form.setCommandListener(this);

// Repeating every 3 seconds
timer = new Timer();
tt = new RunTimerTask();
timer.schedule(tt,0, 3000);
display.setCurrent(form);
}

public void destroyApp (boolean unconditional){}

public void pauseApp () { }

public void commandAction(Command c, Displayable d)
{
if (c == stop)
{
timer.cancel();
}
else if (c == exit)
{
destroyApp(false);
notifyDestroyed();
}
}

/*--------------------------------------------------
* RunTimerTask Class - Run the task
*-------------------------------------------------*/
private class RunTimerTask extends TimerTask
{
public final void run()
{
form.append("count: " + ++count + "\n");
}
}
}

A utility of startTimer

// Starts a timer to run a simple task
private void startTimer( ) {

// Create a task to be run
task = new TimerTask( ) {

private boolean isPaused;
private int count;

public void run( ) {

// Pause or resume the MIDlet.
System.out.println("Timer scheduled");

if (count++ == 4) {

// Terminate the MIDlet
try {

ExampleMIDlet.this.destroyApp(true);

} catch (MIDletStateChangeException ex) {
// Ignore pleas for mercy!
}

ExampleMIDlet.this.notifyDestroyed( );
return;
} // run end

if (isPaused) {

System.out.println(">> Resuming MIDlet");
ExampleMIDlet.this.resumeRequest( );
isPaused = false;

} else {

System.out.println(">> Pausing MIDlet");
isPaused = true;
ExampleMIDlet.this.pauseApp( );
ExampleMIDlet.this.notifyPaused( );

} // if end
} // task end
};

// Create a timer and schedule it to run
timer = new Timer( );

timer.schedule(task, timerInterval, timerInterval);
System.out.println("Timer started.");
}

A MIDlet with Hello text and an Exit command

/*
*
* Copyright (c) 2000 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the confidential and proprietary information of Sun
* Microsystems, Inc. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Sun.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
* THIS SOFTWARE OR ITS DERIVATIVES.
*/

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

/**
* An example MIDlet with simple "Hello" text and an Exit command.
* Refer to the startApp, pauseApp, and destroyApp
* methods so see how each handles the requested transition.
*/
public class HelloCommandMIDlet extends MIDlet implements CommandListener {

private Command exitCommand; // The exit command
private Command okCommand; // The exit command
private Command cancelCommand; // The exit command
private Command nextCommand; // The exit command
private Command backCommand; // The exit command
private Display display; // The display for this MIDlet

public HelloCommandMIDlet() {
display = Display.getDisplay(this);
exitCommand = new Command("Exit", Command.EXIT, 2);
}

/**
* Start up the Hello MIDlet by creating the TextBox and associating
* the exit command and listener.
*/
public void startApp() {
TextBox t = new TextBox("Hello", "Hello World!", 256, 0);

t.addCommand(exitCommand);
t.setCommandListener(this);

display.setCurrent(t);
}

/**
* Pause is a no-op since there are no background activities or
* record stores that need to be closed.
*/
public void pauseApp() {
}

/**
* Destroy must cleanup everything not handled by the garbage collector.
* In this case there is nothing to cleanup.
*/
public void destroyApp(boolean unconditional) {
}

/*
* Respond to commands, including exit
* On the exit command, cleanup and notify that the MIDlet has been destroyed.
*/
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
}

}

Sort mixed records in RMS

/*
J2ME: The Complete Reference

James Keogh

Publisher: McGraw-Hill

ISBN 0072227109

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

*/

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

public class SortMixedRecordDataTypeExample
extends MIDlet implements CommandListener
{
private Display display;
private Alert alert;
private Form form;
private Command exit;
private Command start;
private RecordStore recordstore = null;
private RecordEnumeration recordEnumeration = null;
private Comparator comparator = null;
public SortMixedRecordDataTypeExample ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.SCREEN, 1);
start = new Command("Start", Command.SCREEN, 1);
form = new Form("Mixed RecordEnumeration");
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(true);
notifyDestroyed();
}
else if (command == start)
{
try
{
recordstore = RecordStore.openRecordStore(
"myRecordStore", true );
}
catch (Exception error)
{
alert = new Alert("Error Creating",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
byte[] outputRecord;
String outputString[] = {"Mary", "Bob", "Adam"};
int outputInteger[] = {15, 10, 5};
ByteArrayOutputStream outputStream =
new ByteArrayOutputStream();
DataOutputStream outputDataStream =
new DataOutputStream(outputStream);
for (int x = 0; x < 3; x++)
{
outputDataStream.writeUTF(outputString[x]);
outputDataStream.writeInt(outputInteger[x]);
outputDataStream.flush();
outputRecord = outputStream.toByteArray();
recordstore.addRecord(outputRecord, 0,
outputRecord.length);
outputStream.reset();
}
outputStream.close();
outputDataStream.close();
}
catch ( Exception error)
{
alert = new Alert("Error Writing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
String[] inputString = new String[3];
int z = 0;
byte[] byteInputData = new byte[300];
ByteArrayInputStream inputStream =
new ByteArrayInputStream(byteInputData);
DataInputStream inputDataStream =
new DataInputStream(inputStream);
StringBuffer buffer = new StringBuffer();
comparator = new Comparator();
recordEnumeration = recordstore.enumerateRecords(
null, comparator, false);
while (recordEnumeration.hasNextElement())
{
recordstore.getRecord( recordEnumeration.nextRecordId(),
byteInputData, 0);
buffer.append(inputDataStream.readUTF());
buffer.append(inputDataStream.readInt());
buffer.append("\n");
inputDataStream.reset();
}
alert = new Alert("Reading", buffer.toString(), null,
AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
inputDataStream.close();
inputStream.close();
}
catch (Exception error)
{
alert = new Alert("Error Reading",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
recordstore.closeRecordStore();
}
catch (Exception error)
{
alert = new Alert("Error Closing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
if (RecordStore.listRecordStores() != null)
{
try
{
RecordStore.deleteRecordStore("myRecordStore");
comparator.compareClose();
recordEnumeration.destroy();
}
catch (Exception error)
{
alert = new Alert("Error Removing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
}
}
}
class Comparator implements RecordComparator
{
private byte[] comparatorInputData = new byte[300];
private ByteArrayInputStream comparatorInputStream = null;
private DataInputStream comparatorInputDataType = null;
public int compare(byte[] record1, byte[] record2)
{
int record1int, record2int;
try
{
int maxlen = Math.max(record1.length, record2.length);
if (maxlen > comparatorInputData.length)
{
comparatorInputData = new byte[maxlen];
}
comparatorInputStream = new ByteArrayInputStream(record1);
comparatorInputDataType =
new DataInputStream(comparatorInputStream);
comparatorInputDataType.readUTF();
record1int = comparatorInputDataType.readInt();
comparatorInputStream = new ByteArrayInputStream(record2);
comparatorInputDataType =
new DataInputStream(comparatorInputStream);
comparatorInputDataType.readUTF();
record2int = comparatorInputDataType.readInt();
if (record1int == record2int)
{
return RecordComparator.EQUIVALENT;
}
else if (record1int < record2int)
{
return RecordComparator.PRECEDES;
}
else
{
return RecordComparator.FOLLOWS;
}
}
catch (Exception error)
{
return RecordComparator.EQUIVALENT;
}
}
public void compareClose()
{
try
{
if (comparatorInputStream!= null)
{
comparatorInputStream.close();
}
if (comparatorInputDataType!= null)
{
comparatorInputDataType.close();
}
}
catch (Exception error)
{
}
}
}

How to search a simple record in RMS

/*
J2ME: The Complete Reference

James Keogh

Publisher: McGraw-Hill

ISBN 0072227109

*/

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

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

public class SearchExample extends MIDlet implements CommandListener
{
private Display display;
private Alert alert;
private Form form;
private Command exit;
private Command start;
private RecordStore recordstore = null;
private RecordEnumeration recordEnumeration = null;
private Filter filter = null;
public SearchExample ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.SCREEN, 1);
start = new Command("Start", Command.SCREEN, 1);
form = new Form("Mixed RecordEnumeration", null);
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(true);
notifyDestroyed();
}
else if (command == start)
{
try
{
recordstore = RecordStore.openRecordStore(
"myRecordStore", true );
}
catch (Exception error)
{
alert = new Alert("Error Creating",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
String outputData[] = {"Mary", "Bob", "Adam"};
for (int x = 0 ; x < 3; x++)
{
byte[] byteOutputData = outputData[x].getBytes();
recordstore.addRecord(byteOutputData, 0,
byteOutputData.length);
}
}
catch ( Exception error)
{
alert = new Alert("Error Writing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
filter = new Filter("Bob");
recordEnumeration = recordstore.enumerateRecords(
filter, null, false);
if (recordEnumeration.numRecords() > 0)
{
String string = new String(recordEnumeration.nextRecord());
alert = new Alert("Reading", string,
null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
catch (Exception error)
{
alert = new Alert("Error Reading",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
recordstore.closeRecordStore();
}
catch (Exception error)
{
alert = new Alert("Error Closing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
if (RecordStore.listRecordStores() != null)
{
try
{
RecordStore.deleteRecordStore("myRecordStore");
recordEnumeration.destroy();
filter.filterClose();
}
catch (Exception error)
{
alert = new Alert("Error Removing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
}
}
}
class Filter implements RecordFilter
{
private String search = null;
private ByteArrayInputStream inputstream = null;
private DataInputStream datainputstream = null;
public Filter(String search)
{
this.search = search.toLowerCase();
}
public boolean matches(byte[] suspect)
{
String string = new String(suspect).toLowerCase();
if (string!= null && string.indexOf(search) != -1)
return true;
else
return false;
}
public void filterClose()
{
try
{
if (inputstream != null)
{
inputstream.close();
}
if (datainputstream != null)
{
datainputstream.close();
}
}
catch ( Exception error)
{
}
}
}

How to sort simple records in RMS

/*
J2ME: The Complete Reference

James Keogh

Publisher: McGraw-Hill

ISBN 0072227109

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

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

public class SortExample extends MIDlet implements CommandListener
{
private Display display;
private Alert alert;
private Form form;
private Command exit;
private Command start;
private RecordStore recordstore = null;
private RecordEnumeration recordEnumeration = null;
private Comparator comparator = null;
public SortExample ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.SCREEN, 1);
start = new Command("Start", Command.SCREEN, 1);
form = new Form("Mixed RecordEnumeration", null);
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(true);
notifyDestroyed();
}
else if (command == start)
{
try
{
recordstore = RecordStore.openRecordStore(
"myRecordStore", true );
}
catch (Exception error)
{
alert = new Alert("Error Creating",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
String outputData[] = {"Mary", "Bob", "Adam"};
for (int x = 0; x < 3; x++)
{
byte[] byteOutputData = outputData[x].getBytes();
recordstore.addRecord(byteOutputData, 0,
byteOutputData.length);
}
}
catch ( Exception error)
{
alert = new Alert("Error Writing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
StringBuffer buffer = new StringBuffer();
Comparator comparator = new Comparator();
recordEnumeration = recordstore.enumerateRecords(
null, comparator, false);
while (recordEnumeration.hasNextElement())
{
buffer.append(new String(recordEnumeration.nextRecord()));
buffer.append("\n");
}
alert = new Alert("Reading", buffer.toString() ,
null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
catch (Exception error)
{
alert = new Alert("Error Reading",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
recordstore.closeRecordStore();
}
catch (Exception error)
{
alert = new Alert("Error Closing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
if (RecordStore.listRecordStores() != null)
{
try
{
RecordStore.deleteRecordStore("myRecordStore");
recordEnumeration.destroy();
}
catch (Exception error)
{
alert = new Alert("Error Removing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
}
}
}
class Comparator implements RecordComparator
{
public int compare(byte[] record1, byte[] record2)
{
String string1 = new String(record1),
string2= new String(record2);
int comparison = string1.compareTo(string2);
if (comparison == 0)
return RecordComparator.EQUIVALENT;
else if (comparison < 0)
return RecordComparator.PRECEDES;
else
return RecordComparator.FOLLOWS;
}
}

An example of use of RMS for storing persistent data

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

public class RMSDemo extends MIDlet implements CommandListener {

private Display display;
private RecordStore rs=null;
private Command exit;
private RecordEnumeration re;
private int recordNO;
Form frm;
int index=0;
public RMSDemo() {
display = Display.getDisplay(this);

//Create a RMS
try {
rs= RecordStore.openRecordStore("myRecord",false);
rs.closeRecordStore();
} catch(Exception e) {
System.out.println(e);
}

}

public void startApp() {

frm=new Form("RMSDemo");

exit= new Command("Exit",Command.EXIT,1);
frm.addCommand(exit);

add= new Command("Add",Command.SCREN,1);
frm.addCommand(add);

delete= new Command("Delete",Command.SCREEN,2);
frm.addCommand(delete);

show= new Command("SHOW",Command.SCREEN ,3);
frm.addCommand(show);

frm.setCommandListener(this);
frm.append("#####");
display.setCurrent(frm);
}

public void pauseApp() {

}

public void destroyApp(boolean un) {
}

// Handling commands
public void commandAction(Command cmd,Displayable d) {
if(cmd==add) {
addRecord();
} else
if(cmd==delete) {
removeRecord();
} else
if(cmd==show) {
try {
byte b[]= rs.getRecord(recordNO);
String s= new String(b);
frm.append(s);
} catch(Exception e) {}
}
}


void addRecord() {
try {
rs= RecordStore.openRecordStore("myRecord",false);
index++;
byte b[]=("Record NO "+index).getBytes();
//Adding record to record store
rs.addRecord(b,0,b.length);
rs.closeRecordStore() ;
} catch(Exception e) {
System.out.println(e);
}

}

// Deleting a record
void removeRecord(int recordID) {
try {
rs= RecordStore.openRecordStore("myRecord",false);
rs.deleteRecord(recordID);
index--;
rs.closeRecordStore();
} catch(Exception e) {
System.out.println(e);
}
}


}

Download and view a PNG file

/*--------------------------------------------------
* ViewPng.java
*
* Download and view a png file
*
* 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 ViewPng extends MIDlet implements CommandListener
{
private Display display;
private TextBox tbMain;
private Form fmViewPng;
private Command cmExit;
private Command cmView;
private Command cmBack;

public ViewPng()
{
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/duke.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)
{
// Download image and place on the form
try
{
Image im;
if ((im = getImage(tbMain.getString())) != null)
{
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);
}
else
fmViewPng.append("Unsuccessful download.");
// Display the form with the image
display.setCurrent(fmViewPng);
}
catch (Exception e)
{
System.err.println("Msg: " + e.toString());
}
}
else if (c == cmBack) {
display.setCurrent(tbMain);
}
}

/*--------------------------------------------------
* Open connection and download png into a byte array.
*-------------------------------------------------*/
private Image 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();
bStrm.close();
}

// Create the image from the byte array
im = Image.createImage(imageData, 0, imageData.length);
}
finally
{
// Clean up
if (iStrm != null)
iStrm.close();
if (connection != null)
connection.close();
if (bStrm != null)
bStrm.close();
}
return (im == null ? null : im);
}
}

A sample of graphics - commands and event handling

This example implements the following features in one Midlet:

Implementing Pie Charts and Bar Charts
How to use multiple choices
How to use exclusive lists


/*
* @(#)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);
}
}
}

Displaying images as thumbnails on J2ME devices

Images can be viewed as thumbnails on wireless devices. The method below creates thumbnails from images


private Image createThumbnail(Image image) {
int sourceWidth = image.getWidth();
int sourceHeight = image.getHeight();

int thumbWidth = 64;
int thumbHeight = -1;

if (thumbHeight == -1)
thumbHeight = thumbWidth * sourceHeight / sourceWidth;

Image thumb = Image.createImage(thumbWidth, thumbHeight);
Graphics g = thumb.getGraphics();

for (int y = 0; y < thumbHeight; y++) {
for (int x = 0; x < thumbWidth; x++) {
g.setClip(x, y, 1, 1);
int dx = x * sourceWidth / thumbWidth;
int dy = y * sourceHeight / thumbHeight;
g.drawImage(image, x - dx, y - dy, Graphics.LEFT | Graphics.TOP);
}
}

Image immutableThumb = Image.createImage(thumb);

return immutableThumb;
}

A Midlet application for GIF Animation

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

public class GIFDemo extends MIDlet {

private boolean boolMotion=false;
private int iX=10,iY=60;

Display mDisplay;
Thread th;

public void destroyApp(boolean unconditional){}

public void pauseApp() {}

public void startApp() {
mDisplay = Display.getDisplay(this);

final MyCanvas can = new MyCanvas();

mDisplay.setCurrent(can);
}

}

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

public class MyCanvas extends Canvas implements Runnable {
Image img[]=new Image[3];
public MyCanvas() {
try {
img[0]=Image.createImage("/img1.png");
img[1]=Image.createImage("/img2.png");
img[2]=Image.createImage("/img3.png");

}catch(Exception e){}

Thread th=new Thread(this);
th.start();

}

//Display GIF image
public void paint(Graphics g) {
g.drawImage(img[imgIndex],0,0,g.TOP|g.LEFT);
}

//Handling keyEvents
protected void keyPressed(int keyCode) {

}

public void run() {
while(true) {
imgIndex++;
imgIndex%=3;
try {
Thread.sleep(500);
}catch(Exception e){}
}
}

}

How to relate RGB to gray scale

this is the script to relate RGB to gray scale

g.setGrayScale(127);
System.out.println("Red = " + g.getRedComponent( ) + ", green = " + g.
getGreenComponent( ) + ", blue = " + g.getBlueComponent( ));

Clip region in canvas

/*
J2ME: The Complete Reference

James Keogh

Publisher: McGraw-Hill

ISBN 0072227109

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

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

public class ClippingRegion extends MIDlet{

private Display display;
private MyCanvas canvas;

public ClippingRegion()
{
display = Display.getDisplay(this);
canvas = new MyCanvas(this);
}
protected void startApp()
{
display.setCurrent( canvas );
}
protected void pauseApp()
{
}
protected void destroyApp( boolean unconditional )
{
}
public void exitMIDlet()
{
destroyApp(true);
notifyDestroyed();
}
class MyCanvas extends Canvas implements CommandListener
{
private Command exit;
private ClippingRegion clippingRegion;
private Image image = null;
public MyCanvas (ClippingRegion clippingRegion)
{
this. clippingRegion = clippingRegion;
exit = new Command("Exit", Command.EXIT, 1);
addCommand(exit);
setCommandListener(this);
try
{
image = Image.createImage(70, 70);
Graphics graphics = image.getGraphics();
graphics.setColor(255,0,0);
graphics.fillArc(10, 10, 60, 50, 180, 180);
}
catch (Exception error)
{
Alert alert = new Alert("Failure", "Creating Image",
null, null);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
protected void paint(Graphics graphics)
{
if (image != null)
{
graphics.setColor(255,255,255);
graphics.fillRect(0, 0, getWidth(), getHeight());
graphics.setClip(35, 35, 40, 40);
graphics.drawImage(image, 30, 30,
Graphics.VCENTER | Graphics.HCENTER);
}
}
public void commandAction(Command command, Displayable display)
{
if (command == exit)
{
clippingRegion.exitMIDlet();
}
}
}
}
 

Design by Blogger Buster | Distributed by Blogging Tips