Multiple ChoiceGroup

/*————————————————–
* MultipleChoiceGroup.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 MultipleChoiceGroup extends MIDlet implements ItemStateListener, CommandListener
{
private Display display; // Reference to display object
private Form fmMain; // The main form
private Command cmExit; // A Command to exit the MIDlet
private Command cmView; // View the choice selected
private int selectAllIndex; // Index of the “Select All” option
private ChoiceGroup cgPrefs; // Choice Group of preferences

private int choiceGroupIndex; // Index of choice group on form

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

// Create a multiple choice group
cgPrefs = new ChoiceGroup(”Preferences”, Choice.MULTIPLE);

// Append options, with no associated images
cgPrefs.append(”Auto Indent”, null);
cgPrefs.append(”Replace Tabs”, null);
cgPrefs.append(”Wrap Text”, null);
selectAllIndex = cgPrefs.append(”Select All”, null);

cmExit = new Command(”Exit”, Command.EXIT, 1);
cmView = new Command(”View”, Command.SCREEN,2);

// Create Form, add components, listen for events
fmMain = new Form(”");
choiceGroupIndex = fmMain.append(cgPrefs);
fmMain.addCommand(cmExit);
fmMain.addCommand(cmView);
fmMain.setCommandListener(this);
fmMain.setItemStateListener(this);
}

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

public void pauseApp()
{ }

public void destroyApp(boolean unconditional)
{ }

public void commandAction(Command c, Displayable s)
{
if (c == cmView)
{
boolean selected[] = new boolean[cgPrefs.size()];

// Fill array indicating whether each element is checked
cgPrefs.getSelectedFlags(selected);

for (int i = 0; i < cgPrefs.size(); i++)
System.out.println(cgPrefs.getString(i) + (selected[i] ? “: selected” : “: not selected”));

}
else if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
}

public void itemStateChanged(Item item)
{
if (item == cgPrefs)
{
// Is “Select all” option checked ?
if (cgPrefs.isSelected(selectAllIndex))
{
// Set all checkboxes to true
for (int i = 0; i < cgPrefs.size() - 1; i++)
cgPrefs.setSelectedIndex(i, true);

// Remove the check by “Select All”
cgPrefs.setSelectedIndex(selectAllIndex, false);
}
}
}
}

ChoiceGroup With Image

/*————————————————–
* ChoiceGroupWithImages.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 ChoiceGroupWithImages extends MIDlet implements CommandListener
{
private Display display; // Reference to display object
private Form fmMain; // Main form
private Command cmExit; // Command to exit the MIDlet
private Command cmView; // View the choice selected
private ChoiceGroup cgPrefs; // Choice Group of preferences

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

try
{
// Create array of image objects
Image images[] = {Image.createImage(”/up.png”), Image.createImage(”/down.png”),
Image.createImage(”/help.png”) };

// Create array of corresponding string objects
String options[] = {”Upload”, “Download”, “Help”};

// Create a choice group using arrays
cgPrefs = new ChoiceGroup(”Select Option:”, Choice.EXCLUSIVE, options, images);

}
catch (java.io.IOException e)
{
System.err.println(”Unable to locate or read .png file”);
}

cmExit = new Command(”Exit”, Command.EXIT, 1);
cmView = new Command(”View”, Command.SCREEN,2);

// Create Form, add components, listen for events
fmMain = new Form(”");
fmMain.append(cgPrefs);
fmMain.addCommand(cmExit);
fmMain.addCommand(cmView);
fmMain.setCommandListener(this);
}

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

public void pauseApp()
{ }

public void destroyApp(boolean unconditional)
{ }

public void commandAction(Command c, Displayable s)
{
if (c == cmView)
{
boolean selected[] = new boolean[cgPrefs.size()];

// Fill array indicating whether each element is checked
cgPrefs.getSelectedFlags(selected);

// Print to console the status of each element
for (int i = 0; i < cgPrefs.size(); i++)
System.out.println(cgPrefs.getString(i) + (selected[i] ? “: selected” : “: not selected”));
}
else if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
}
}

GUI Test in Midlet

/*
Learning Wireless Java
Help for New J2ME Developers
By Qusay Mahmoud
ISBN: 0-596-00243-2

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

public class GuiTests extends MIDlet implements CommandListener {
// display manager
Display display = null;

// a menu with items
List menu = null; // main menu

// list of choices
List choose = null;

// textbox
TextBox input = null;

// ticker
Ticker ticker = new Ticker(”Test GUI Components”);

// alerts
final Alert soundAlert = new Alert(”sound Alert”);

// date
DateField date = new DateField(”Today’s date: “, DateField.DATE);

// form
Form form = new Form(”Form for Stuff”);

// gauge
Gauge gauge = new Gauge(”Progress Bar”, false, 20, 9);

// text field
TextField textfield = new TextField(”TextField Label”, “abc”, 50, 0);

// command
static final Command backCommand = new Command(”Back”, Command.BACK, 0);
static final Command mainMenuCommand = new Command(”Main”, Command.SCREEN, 1);
static final Command exitCommand = new Command(”Exit”, Command.STOP, 2);
String currentMenu = null;

// constructor.
public GuiTests() {
}

/**
* Start the MIDlet by creating a list of items and associating the
* exit command with it.
*/
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
// open a db stock file

menu = new List(”Test Components”, Choice.IMPLICIT);
menu.append(”Test TextBox”, null);
menu.append(”Test List”, null);
menu.append(”Test Alert”, null);
menu.append(”Test Date”, null);
menu.append(”Test Form”, null);
menu.addCommand(exitCommand);
menu.setCommandListener(this);
menu.setTicker(ticker);

mainMenu();
}

public void pauseApp() {
display = null;
choose = null;
menu = null;
ticker = null;
form = null;
input = null;
gauge = null;
textfield = null;
}

public void destroyApp(boolean unconditional) {
notifyDestroyed();
}

// main menu
void mainMenu() {
display.setCurrent(menu);
currentMenu = “Main”;
}

/**
* Test the TextBox component.
*/
public void testTextBox() {
input = new TextBox(”Enter Some Text:”, “”, 10, TextField.ANY);
input.setTicker(new Ticker(”Testing TextBox”));
input.addCommand(backCommand);
input.setCommandListener(this);
input.setString(”");
display.setCurrent(input);
currentMenu = “input”;
}

/**
* Test the List component.
*/
public void testList() {
choose = new List(”Choose Items”, Choice.MULTIPLE);
choose.setTicker(new Ticker(”Testing List”));
choose.addCommand(backCommand);
choose.setCommandListener(this);
choose.append(”Item 1″, null);
choose.append(”Item 2″, null);
choose.append(”Item 3″, null);
display.setCurrent(choose);
currentMenu = “list”;
}

/**
* Test the Alert component.
*/
public void testAlert() {
soundAlert.setType(AlertType.ERROR);
//soundAlert.setTimeout(20);
soundAlert.setString(”** ERROR **”);
display.setCurrent(soundAlert);
}

/**
* Test the DateField component.
*/
public void testDate() {
java.util.Date now = new java.util.Date();
date.setDate(now);
Form f = new Form(”Today’s date”);
f.append(date);
f.addCommand(backCommand);
f.setCommandListener(this);
display.setCurrent(f);
currentMenu = “date”;
}

/**
* Test the Form component.
*/
public void testForm() {
form.append(gauge);
form.append(textfield);
form.addCommand(backCommand);
form.setCommandListener(this);
display.setCurrent(form);
currentMenu = “form”;
}

/**
* Handle events.
*/
public void commandAction(Command c, Displayable d) {
String label = c.getLabel();
if (label.equals(”Exit”)) {
destroyApp(true);
} else if (label.equals(”Back”)) {
if(currentMenu.equals(”list”) || currentMenu.equals(”input”) ||
currentMenu.equals(”date”) || currentMenu.equals(”form”)) {
// go back to menu
mainMenu();
}

} else {
List down = (List)display.getCurrent();
switch(down.getSelectedIndex()) {
case 0: testTextBox();break;
case 1: testList();break;
case 2: testAlert();break;
case 3: testDate();break;
case 4: testForm();break;
}

}
}
}

TextBox Capture

/*
J2ME: The Complete Reference

James Keogh

Publisher: McGraw-Hill

ISBN 0072227109

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

*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class TextBoxCapture extends MIDlet implements CommandListener
{
private Display display;
private TextBox textbox;
private Command submit;
private Command exit;
public TextBoxCapture()
{
display = Display.getDisplay(this);
submit = new Command(”Submit”, Command.SCREEN, 1);
exit = new Command(”Exit”, Command.EXIT, 1);
textbox = new TextBox(”First Name:”, “”, 30, TextField.ANY);
textbox.addCommand(exit);
textbox.addCommand(submit);
textbox.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(textbox);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command command, Displayable displayable)
{
if (command == submit)
{
textbox.setString(”Hello, ” + textbox.getString());
textbox.removeCommand(submit);
}
else if (command == exit)
{
destroyApp(false);
notifyDestroyed();
}
}
}

TextField Capture

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

*/
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.TextField;
import javax.microedition.midlet.MIDlet;

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

private Form form = new Form(”Sign In Please”);

private Command submit = new Command(”Submit”, Command.SCREEN, 1);

private Command exit = new Command(”Exit”, Command.EXIT, 1);

private TextField textfield = new TextField(”First Name:”, “”, 30, TextField.ANY);

public TextFieldCapture() {
display = Display.getDisplay(this);
form.addCommand(exit);
form.addCommand(submit);
form.append(textfield);
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 == submit) {
textfield.setString(”Hello, ” + textfield.getString());
form.removeCommand(submit);
} else if (command == exit) {
destroyApp(false);
notifyDestroyed();
}
}
}

Basic RMS Example

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);
}
}

}

Font Demo J2ME

The Font class represents fonts and font metrics. Fonts cannot be created by applications. The setFont(Font font) method of graphic class sets the font for all subsequent text rendering operations. And there is no call to showNotify and hideNotify method on some the device. This application will help game developer to find out the exact behaviour of mobile device.

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

public class FontDemo 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 {

Font font;
String msg;
public MyCanvas() {

font=Font.getFont(Font.FACE_MONOSPACE,
Font.STYLE_ITALIC, Font.SIZE_LARGE);
msg = “Font:FACE_MONOSPACE Font.STYLE_ITALIC Font.SIZE_LARGE”;
}

public void paint(Graphics g) {
g.setFont(font);
g.drawString(msg,0,10,g.TOP|g.LEFT);
g.drawString(”press NUM KEY: 1 2 or 3″,0,80,g.TOP|g.LEFT);
}

void changeValue(int change) {
switch(change) {
case ‘1′:
font=Font.getFont(Font.FACE_MONOSPACE,
Font.STYLE_ITALIC, Font.SIZE_LARGE) ;
msg=”Font:FACE_MONOSPACE Font.STYLE_ITALIC “+
“Font.SIZE_LARGE”;
break;
case ‘2′:
font=Font.getFont(Font.FACE_PROPORTIONAL,
Font.STYLE_ITALIC, Font.SMALL) ;
msg = “Font:FACE_PROPORTIONAL Font.STYLE_ITALIC “+
“Font.SIZE_SMALL”;
break;
case ‘3′:
font=Font.getFont(Font.FACE_SYSTEM ,
Font.STYLE_BOLD, Font.SIZE_LARGE) ;
msg=”Font:FACE_SYSTEM Font.STYLE_BOLD “+
“Font.SIZE_LARGE”;
break;
}
}

//Handling keyEvents
protected void keyPressed(int keyCode) {
changeValue(keyCode);
repaint();
}

}

Capturing Video with J2ME

Illustration below takes pictures on a J2ME device.

import java.io.IOException;
import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.media.control.VideoControl;

public class VideoMIDlet extends MIDlet implements CommandListener {

private Display display;
private Form form;
private Command exit,back,capture,camera;
private Player player;
private VideoControl videoControl;
private Video video;

public VideoMIDlet() {

exit = new Command(”Exit”, Command.EXIT, 0);
camera = new Command(”Camera”, Command.SCREEN, 0);
back = new Command(”Back”, Command.BACK, 0);
capture = new Command(”Capture”, Command.SCREEN, 0);

form = new Form(”Capture Video”);
form.addCommand(camera);
form.setCommandListener(this);
}

public void startApp() {
display = Display.getDisplay(this);
display.setCurrent(form);
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable s) {
if (c == exit) {
destroyApp(true);
notifyDestroyed();
} else if (c == camera) {
showCamera();
} else if (c == back)
display.setCurrent(form);
else if (c == capture) {
video = new Video(this);
video.start();
}
}

public void showCamera() {
try {
player = Manager.createPlayer(”capture://video”);
player.realize();

videoControl = (VideoControl)player.getControl(”VideoControl”);
Canvas canvas = new VideoCanvas(this, videoControl);
canvas.addCommand(back);
canvas.addCommand(capture);
canvas.setCommandListener(this);
display.setCurrent(canvas);
player.start();
} catch (IOException ioe) {} catch (MediaException me) {}
}

class Video extends Thread {
videoMIDlet midlet;
public Video(VideoMIDlet midlet) {
this.midlet = midlet;
}

public void run() {
captureVideo();

}

public void captureVideo() {
try {
byte[] raw = videoControl.getSnapshot(null);
Image image = Image.createImage(raw, 0, raw.length);
form.append(image);
display.setCurrent(form);

player.close();
player = null;
videoControl = null;
} catch (MediaException me) { }
}
};
}

import javax.microedition.lcdui.*;
import javax.microedition.media.MediaException;
import javax.microedition.media.control.VideoControl;

public class VideoCanvas extends Canvas {
private VideoMIDlet midlet;

public VideoCanvas(VideoMIDlet midlet, VideoControl videoControl) {
int width = getWidth();
int height = getHeight();
this.midlet = midlet;

videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
try {
videoControl.setDisplayLocation(2, 2);
videoControl.setDisplaySize(width - 4, height - 4);
} catch (MediaException me) {}
videoControl.setVisible(true);
}

public void paint(Graphics g) {
int width = getWidth();
int height = getHeight();

g.setColor(0×00ff00);
g.drawRect(0, 0, width - 1, height - 1);
g.drawRect(1, 1, width - 3, height - 3);
}

Vibrate Phone

You can make your phone migrate in J2ME by calling vibrate(int duration) method of javax.microedition.lcdui.Display class. The duration parameter is the number of milliseconds the vibrator should be run.

Display.getDisplay(this).vibrate(800);

Playing local MP3

The method below creates player and play mp3 file.
public void run()
{
try
{
InputStream is = getClass().getResourceAsStream(”/your.mp3″);
player = Manager.createPlayer(is,”audio/mpeg”);

player.realize();
// get volume control for player and set volume to max
vc = (VolumeControl) player.getControl(”VolumeControl”);
if(vc != null)
{
vc.setLevel(100);
}
player.prefetch();
player.start();
}
catch(Exception e)
{}
}