Friday, 24 February 2012

A Model PIM Application

import javax.microedition.pim.*;
import java.util.Enumeration;
import java.util.Calendar;
import java.util.Date;
public class PIMTest {
public PIMTest() {
}
/********************************************
* Contact/ContactList sample code
**********************************************/
public void createAContact() {
// Create a support contact entry in the device's
//local address bookso that users have the contact
//information for anything that they
// need help with about your application
PIM pim = PIM.getInstance();
ContactList cl = null;
Contact new_contact = null;
try {
// Open write only since you're just going to
// add your support contact
// info to the device's database
cl = (ContactList)
pim.openPIMList(PIM.CONTACT_LIST, PIM.WRITE_ONLY);
} catch (PIMException e) {
// failed opening the default contact list!
// Error case - abort this attempt
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request for
//write access to contact list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't add the contact");
return;
}
// Create an "empty" contact to work with
new_contact = cl.createContact();
// Add your company's info: company name,
//two support phone numbers, a support
// email, and a note about what product the user has. Add whatever
// information the native contact list
//supports and don't add it if
// the field is not supported.
if (cl.isSupportedField(Contact.ORG))
new_contact.addString(Contact.ORG, PIMItem.ATTR_NONE,
"Acme, Inc.");
if (cl.isSupportedField(Contact.TEL)) {
new_contact.addString(Contact.TEL, PIMItem.ATTR_NONE,
"800-888-8888");
new_contact.addString(Contact.TEL, PIMItem.ATTR_NONE,
"800-888-8889");
}
if (cl.isSupportedField(Contact.EMAIL))
new_contact.addString(Contact.EMAIL,
PIMItem.ATTR_NONE, "support@acme.com");
if (cl.isSupportedField(Contact.NOTE))
new_contact.addString(Contact.NOTE, PIMItem.ATTR_NONE,
"You've purchased application with registration number NNN.");
try {
// commits it to the list and the native database
new_contact.commit();
}
catch (PIMException e) {
// failed committing the contact
System.err.println(
"This application cannot add the contact info");
}
try {
l.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void retrieveContacts() {
// Get all contacts with last name starting with "S" (e.g.
// Smith, Sanders, Stargell, etc.) for a listing screen
PIM pim = PIM.getInstance();
ContactList cl = null;
Contact search_template = null;
Enumeration s_contacts = null;
try {
cl = (ContactList) pim.openPIMList(PIM.CONTACT_LIST,
PIM.READ_ONLY);
} catch (PIMException e) {
// failed opening the default contact list!
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request for
// read access to contact list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't get contacts");
return;
}
// first create a "template" contact which we'll use for matching
search_template = cl.createContact();
if (cl.isSupportedArrayElement(Contact.NAME,
Contact.NAME_FAMILY)) {
// this particular contact list does contain last names, so we
// can now do the search
// now fill in the search parameters of last name
// starting with 'S'
String[] name_struct = new String[Contact.NAMESIZE];
name_struct[Contact.NAME_FAMILY] = "S";
search_template.addStringArray(Contact.NAME,
PIMItem.ATTR_NONE, name_struct);
}
else if (cl.isSupportedField(Contact.FORMATTED_NAME)) {
// the contact implementation doesn't have individual name
// fields, so try the single name field FORMATTED_NAME
search_template.addString(Contact.FORMATTED_NAME,
PIMItem.ATTR_NONE, "S");
}
try {
// Get the enumeration of matching elements
s_contacts = cl.items(search_template);
} catch (PIMException e) {
// failed to retrieve elements due to error!
System.err.println(
"This application cannot retrieve the contacts");
}
try {
cl.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void modifyAContact() {
// Code sample:
// Update John Smith's home phone number
// from "555-0000" to "555-1212"
// since he moved...
PIM pim = PIM.getInstance();
ContactList cl = null;
Enumeration contacts = null;
try {
cl = (ContactList) pim.openPIMList(
PIM.CONTACT_LIST, PIM.READ_WRITE);
} catch (PIMException e) {
// failed opening the default contact list!
System.err.println(
"This application failed to open the contact list");
} catch (SecurityException e) {
// user rejected application's request
// for read/write access to contact list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't get contacts");
return;
}
// first create a "template" contact which we'll use for matching
// to find John Smith's contact entry
Contact template = cl.createContact();
String tel_number = "";
if (cl.isSupportedField(Contact.NAME)) {
String[] name_struct = new String[Contact.NAMESIZE];
name_struct[Contact.NAME_FAMILY] = "Smith";
name_struct[Contact.NAME_FAMILY] = "John";
template.addStringArray(
Contact.NAME, PIMItem.ATTR_NONE, name_struct);
}
if (cl.isSupportedField(Contact.TEL)) {
template.addString(Contact.TEL, Contact.ATTR_HOME, "555-0000");
}
try {
// Get the enumeration of matching elements
contacts = cl.items(template);
} catch (PIMException e) {
// failed retrieving the items enumeration due to an error
System.err.println(
"This application cannot retrieve the contact");
}
// update all John Smith entries with old home numbers of 555-0000
while (contacts!= null && contacts.hasMoreElements()) {
Contact c = (Contact) contacts.nextElement();
for (int index = c.countValues(Contact.TEL); index != 0; index--)
{
if (c.getString(Contact.TEL, index).equals("555-0000")) {
c.setString(Contact.TEL, index, Contact.ATTR_HOME,
"555-1212");
try {
// save change to the database
c.commit();
} catch (PIMException e) {
// Oops couldn't save the data...
System.err.println(
"This application cannot commit the contact info");
}
break; // go to next matching element
}
}
}
try {
cl.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void deleteContacts() {
// Delete all contacts at company WorldCom
// since they won't be answering
// phone calls anymore...
PIM pim = PIM.getInstance();
ContactList cl = null;
Enumeration contacts = null;
try {
cl = (ContactList) pim.openPIMList(
 PIM.CONTACT_LIST, PIM.READ_WRITE);
} catch (PIMException e) {
// failed opening the default contact list!
System.err.println(
"This application failed to open the contact list");
return;
} catch (SecurityException e) {
// user rejected application's request for
// read/write access to contact list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't get contacts");
return;
}
// first create a "template" contact which we'll use for matching
// to find WorldCom contact entries
Contact template = cl.createContact();
if (cl.isSupportedField(Contact.ORG)) {
template.addString(Contact.ORG,
PIMItem.ATTR_NONE, "WorldCom");
try {
// Get the enumeration of matching elements
contacts = cl.items(template);
} catch (PIMException e) {
// failed retrieving the items enumeration due to an error
System.err.println(
"This application cannot commit the contact info");
}
}
// delete all WorldCom entries
while (contacts != null && contacts.hasMoreElements()) {
Contact c = (Contact) contacts.nextElement();
try {
cl.removeContact(c);
} catch (PIMException e) {
// couldn't delete the entry for some
// reason (probably shredded)
System.err.println(
"This application cannot remove the contact info");
}
}
try {
cl.close();
} catch (PIMException e) {
// failed to close the list
}
}
/********************************************
* Event/EventList sample code
**********************************************/
public void createAnEvent() {
// Create an event entry in the device's local calendar
// reminding the user to register your application
PIM pim = PIM.getInstance();
EventList el = null;
Event new_event = null;
try {
// Open write only since you're just going to
//add your registration
// event info to the device's database
el = (EventList) pim.openPIMList(
PIM.EVENT_LIST, PIM.WRITE_ONLY);
} catch (PIMException e) {
// failed opening the default event list!
// Error case - abort this attempt
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request
// for write access to event list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't add the event");
return;
}
// Create an "empty" event to work with
new_event = el.createEvent();
// Add a registration reminder event:
// make it two weeks from now with an
// alarm 10 minutes before the occurrence, and
// add a note with the phone or email to call.
if (el.isSupportedField(Event.START)) {
Date d = new Date();
long l = d.getTime() + (long)1209600000;
new_event.addDate(Event.START, PIMItem.ATTR_NONE, l);
}
if (el.isSupportedField(Event.ALARM))
new_event.addInt(Event.ALARM, PIMItem.ATTR_NONE, 600);
if (el.isSupportedField(Event.SUMMARY))
new_event.addString(Event.SUMMARY, PIMItem.ATTR_NONE,
"Register Your Product!");
if (el.isSupportedField(Event.NOTE))
new_event.addString(Event.NOTE, PIMItem.ATTR_NONE,
"You've purchased application XXX with registration number NNN.
Please register it now. Look in the Contact List
for information on how to contact us.");
try {
// commits it to the list and the native database
new_event.commit();
}
catch (PIMException e) {
// failed committing the event
System.err.println("This application cannot add the event")
}
try {
el.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void retrieveEvents() {
// Get all events occurring for the coming week,
// for a listing screen
PIM pim = PIM.getInstance();
EventList el = null;
Event search_template = null;
Enumeration this_weeks_events = null;
try {
el = (EventList) pim.openPIMList(
PIM.EVENT_LIST, PIM.READ_ONLY);
} catch (PIMException e) {
// failed opening the default event list!
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request for
// read access to event list
// This is not an error condition and can be normal
System.out.println("Okay, this application won't get events");
return;
}
// calculate today's date and next week's date
long current_time = (new Date()).getTime();
long next_week = current_time + 604800000;
try {
// Get the enumeration of matching elements
this_weeks_events = el.items(
EventList.OCCURRING, current_time, next_week, true);
} catch (PIMException e) {
// failed to retrieve elements due to error!
// Error case - abort this attempt
System.err.println(
"This application cannot retrieve the events");
}
try {
el.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void modifyEvents() {
// Code sample:
// Postpone all events from today until
// tomorrow (sick day today...)
PIM pim = PIM.getInstance();
EventList el = null;
Enumeration todays_events = null;
try {
el = (EventList) pim.openPIMList(
PIM.EVENT_LIST, PIM.READ_WRITE);
} catch (PIMException e) {
// failed opening the default event list!
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request
for read/write access to contact list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't modify any event");
return;
}
// calculate today's start and end times
Calendar start_of_day = Calendar.getInstance();
// start of work day is 7am
start_of_day.set(Calendar.HOUR_OF_DAY, 7);
Calendar end_of_day = Calendar.getInstance();
// end of work day is 8pm
end_of_day.set(Calendar.HOUR_OF_DAY, 20);
try {
// Get the enumeration of matching elements
todays_events = el.items(Event.OCCURRING,
start_of_day.getTime().getTime(), end_of_day.getTime().getTime(), true);
} catch (PIMException e) {
// failed to retrieve elements due to error!
System.err.println(
"This application cannot retrieve the events");
}
// update all events by one day
while (todays_events != null && todays_events.hasMoreElements()) {
Event e = (Event) todays_events.nextElement();
e.setDate(Event.START, 0, PIMItem.ATTR_NONE,
e.getDate(Event.START, 0) + 86400000);
try {
// save change to the database
e.commit();
} catch (PIMException exe) {
// Oops couldn't save the data...
System.err.println(
"This application cannot commit the event");
}
}
try {
el.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void deleteEvents() {
// Delete all events having to do with Christmas (bah humbug!)
PIM pim = PIM.getInstance();
EventList el = null;
Enumeration xmas_events = null;
try {
el = (EventList) pim.openPIMList(
PIM.EVENT_LIST, PIM.READ_WRITE);
} catch (PIMException e) {
// failed opening the default event list!
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request
// for read/write access to event list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't modify any event");
return;
}
try {
// Get the enumeration of matching eleme
} catch (PIMException e) {
// failed retrieving the items enumeration due to an error
System.err.println(
"This application cannot retrieve the events");
return;
}
// delete all event entries containing Christmas
while (xmas_events != null && xmas_events.hasMoreElements()) {
Event e = (Event) xmas_events.nextElement();
try {
el.removeEvent(e);
} catch (PIMException exe) {
// couldn't delete the entry for some reason
System.err.println(
"This application cannot remove the event info");
}
}
try {
el.close();
} catch (PIMException e) {
// failed to close the list
}
}
/****************************************************
* ToDo/ToDoList sample code
******************************************************/
public void createAToDo() {
// Create a todo entry in the device's local todo list
// reminding the user to register your application
PIM pim = PIM.getInstance();
ToDoList tl = null;
ToDo new_todo = null;
try {
// Open write only since you're just going to
// add your registration
// todo info to the device's todo database
tl = (ToDoList) pim.openPIMList(PIM.TODO_LIST, PIM.WRITE_ONLY);
} catch (PIMException e) {
// failed opening the default todo list!
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request
// for write access to todo list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't add the todo");
return;
}
// Create an "empty" todo to work with
new_todo = tl.createToDo();
// Add a registration todo: make it have a
// due date of two weeks from now
// with a low priority, and
// add a note with the phone or email to call.
if (tl.isSupportedField(ToDo.DUE)) {
Date d = new Date();
long l = d.getTime() + (long)1209600000;
new_todo.addDate(ToDo.DUE, PIMItem.ATTR_NONE, l);
}
if (tl.isSupportedField(ToDo.PRIORITY))
new_todo.addInt(ToDo.PRIORITY, PIMItem.ATTR_NONE, 5);
if (tl.isSupportedField(ToDo.SUMMARY))
new_todo.addString(ToDo.SUMMARY, PIMItem.ATTR_NONE,
"Register Your Product!");
if (tl.isSupportedField(ToDo.NOTE))
new_todo.addString(ToDo.NOTE, PIMItem.ATTR_NONE,
"You've purchased application XXX with
registration number NNN. Please register it now.
Look in the Contact List for information on
how to contact us.");
try {
// commits it to the list and the native database
new_todo.commit();
}
catch (PIMException e) {
// failed committing the todo
System.err.println("This application cannot add the todo");
}
try {
tl.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void retrieveToDos() {
// Get all todos due today, for a listing screen
PIM pim = PIM.getInstance();
ToDoList tl = null;
ToDo search_template = null;
Enumeration todos = null;
try {
tl = (ToDoList) pim.openPIMList(PIM.TODO_LIST, PIM.READ_ONLY);
} catch (PIMException e) {
// failed opening the default todo list!
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request for
// read access to todo list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't get todo items");
return;
}
// calculate today's start and end times
Calendar start_of_day = Calendar.getInstance();
start_of_day.set(Calendar.HOUR_OF_DAY, 0);
Calendar end_of_day = Calendar.getInstance();
end_of_day.set(Calendar.HOUR_OF_DAY, 24);
try {
// Get the enumeration of matching elements
todos = tl.items(
ToDo.DUE, start_of_day.getTime().getTime(),
end_of_day.getTime().getTime());
} catch (PIMException e) {
// failed to retrieve elements due to error!
// Error case - abort this attempt
System.err.println(
"This application cannot retrieve the todos");
}
try {
tl.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void modifyToDos() {
// Mark all stuff from yesterday as completed
PIM pim = PIM.getInstance();
ToDoList tl = null;
ToDo search_template = null;
Enumeration todos = null;
try {
tl = (ToDoList) pim.openPIMList(PIM.TODO_LIST, PIM.READ_ONLY);
} catch (PIMException e) {
// failed opening the default todo list!
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request for
// read access to todo list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't get todo items");
return;
}
// calculate today's start and end times
Calendar start_of_day = Calendar.getInstance();
start_of_day.set(Calendar.HOUR_OF_DAY, 0);
Calendar end_of_day = Calendar.getInstance();
end_of_day.set(Calendar.HOUR_OF_DAY, 24);
try {
// Get the enumeration of matching elements
todos = tl.items(
ToDo.DUE, start_of_day.getTime().getTime() - 86400000,
end_of_day.getTime().getTime() - 86400000);
} catch (PIMException e) {
// failed to retrieve elements due to error!
// Error case - abort this attempt
System.err.println("This application cannot retrieve the todos");
}
// set all todos due yesterday to completed
//with updated completion date
while (todos != null && todos.hasMoreElements()) {
ToDo t = (ToDo) todos.nextElement();
if (tl.isSupportedField(ToDo.COMPLETED))
t.setBoolean(ToDo.COMPLETED, 0, PIMItem.ATTR_NONE, true);
if (tl.isSupportedField(ToDo.COMPLETION_DATE))
t.setDate(ToDo.COMPLETION_DATE, 0,
PIMItem.ATTR_NONE, (new Date()).getTime());
try {
// save change to the database
t.commit();
} catch (PIMException exe) {
// Oops couldn't save the data...
System.err.println(
"This application cannot commit the todo");
}
}
try {
tl.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void deleteToDos() {
// Delete all ToDos having to do with
cleaning (hired a maid instead)
PIM pim = PIM.getInstance();
ToDoList tl = null;
Enumeration todos = null;
try {
tl = (ToDoList) pim.openPIMList(PIM.TODO_LIST, PIM.READ_WRITE);
} catch (PIMException e) {
// failed opening the default todo list!
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request
// for read/write access to todo list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't modify any todo");
return;
}
try {
// Get the enumeration of matching elements
todos = tl.items("clean");
} catch (PIMException e) {
// failed retrieving the items enumeration due to an error
System.err.println(
"This application cannot retrieve the todos");
return;
}
// delete all event entries containing 'clean'
while (todos != null && todos.hasMoreElements()) {
ToDo t = (ToDo) todos.nextElement();
try {
tl.removeToDo(t);
} catch (PIMException exe) {
// couldn't delete the entry for some reason
System.err.println(
"This application cannot remove the todo info");
}
}
try {
tl.close();
} catch (PIMException e) {
// failed to close the list
}
}
}


Creating an Instance of the Gauge Class

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class GaugeNonInteractive
extends MIDlet implements CommandListener
{
private Display display;
private Form form;
private Command exit;
private Command start;
private Gauge gauge;
private boolean isSafeToExit;
public GaugeNonInteractive()
{
display = Display.getDisplay(this);
gauge = new Gauge("Progress Tracking", false, 100, 0);
exit = new Command("Exit", Command.EXIT, 1);
start = new Command("Start", Command.SCREEN, 1);
form = new Form("");
form.append(gauge);
form.addCommand(start);
form.addCommand(exit);
form.setCommandListener(this);
isSafeToExit = true;
}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
throws MIDletStateChangeException
{
if (!unconditional)
{
throw new MIDletStateChangeException();
}
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
try
{
destroyApp(isSafeToExit);
notifyDestroyed();
}
catch (MIDletStateChangeException Error)
{
Alert alert = new Alert("Busy", "Please try again.", null, AlertType.WARNING);
alert.setTimeout(1500);
display.setCurrent(alert, form);
}
}
else if (command == start)
{
form.remove.Command(start);
new Thread(new GaugeUpdater()).start();
}
}
class GaugeUpdater implements Runnable
{
GaugeUpdater()
{
}
public void run()
{
isSafeToExit = false;
try
{
while (gauge.getValue() < gauge.getMaxValue())
{
Thread.sleep(1000);
gauge.setValue(gauge.getValue() + 1);
}
isSafeToExit = true;
gauge.setLabel("Process Completed.");
}
catch (InterruptedException Error)
{
throw new RuntimeException(Error.getMessage());
}
}
}
}

Creating an Instance of the DateField Class

import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class DateToday extends MIDlet implements CommandListener
{
private Display display;
private Form form;
private Date today;
private Command exit;
private DateField datefield;
public DateToday()
{
display = Display.getDisplay(this);
form = new Form("Today's Date");
today = new Date(System.currentTimeMillis());
datefield = new DateField("", DateField.DATE_TIME);
datefield.setDate(today);
exit = new Command("Exit", Command.EXIT, 1);
form.append(datefield);
form.addCommand(exit);
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();
}
}
}

Creating Radio Buttons

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class RadioButtons extends MIDlet implements CommandListener
{
private Display display;
private Form form;
private Command exit;
private Command process;
private ChoiceGroup gender;
private int currentIndex;
private int genderIndex;
public RadioButtons()
{
display = Display.getDisplay(this);
gender = new ChoiceGroup("Enter Gender", Choice.EXCLUSIVE);
gender.append("Female", null);
currentIndex = gender.append("Male ", null);
gender.setSelectedIndex(currentIndex, true);
exit = new Command("Exit", Command.EXIT, 1);
process = new Command("Process", Command.SCREEN,2);
form = new Form("Gender");
genderIndex = form.append(gender);
form.addCommand(exit);
form.addCommand(process);
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 == process)
{
currentIndex = gender.getSelectedIndex();
StringItem message = new StringItem("Gender: ",
gender.getString(currentIndex));
form.append(message);
form.delete(genderIndex);
form.removeCommand(process);
}
}
}

Creating Check Boxes

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class CheckBoxes extends MIDlet implements CommandListener
{
private Display display;
private Form form;
private Command exit;
private Command process;
private ChoiceGroup movies;
private int movieIndex;
public CheckBoxes()
{
display = Display.getDisplay(this);
movies = new ChoiceGroup("Select Movies You Like to See",
Choice.MULTIPLE);
movies.append("Action", null);
movies.append("Romance", null);
movies.append("Comedy", null);
movies.append("Horror", null);
exit = new Command("Exit", Command.EXIT, 1);
process = new Command("Process", Command.SCREEN,2);
form = new Form("Movies");
movieIndex = form.append(movies);
form.addCommand(exit);
form.addCommand(process);
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 == process)
{
boolean picks[] = new boolean[movies.size()];
StringItem message[] = new StringItem[movies.size()];
movies.getSelectedFlags(picks);
for (int x = 0; x < picks.length; x++)
{
if (picks[x])
{
message[x] = new StringItem("",movies.getString(x)+"\n");
form.append(message[x]);
}
}
form.delete(movieIndex);
form.removeCommand(process);
}
else if (command == exit)
{
destroyApp(false);
notifyDestroyed();
}
}
}

Creating an Instance of the Form Class

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class CreatingFormWithItems
extends MIDlet implements CommandListener
{
private Display display;
private Form form;
private Command exit;
public CreatingFormWithItems ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.SCREEN, 1);
StringItem messages[] = new StringItem[2];
message[0] = new StringItem("Welcome, ", "glad you could come.");
message[1] = new StringItem("Hello, ", "Mary.");
form = new Form("Display Form with Items", messages);
form.addCommand(exit);
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();
}
}
}

Creating an Alert Dialog Box

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class DisplayAlert extends MIDlet implements CommandListener
{
private Display display;
private Alert alert;
private Form form;
private Command exit;
private boolean exitFlag;
public DisplayAlert()
{
exitFlag = false;
display = Display.getDisplay(this);
exit = new Command("Exit", Command.SCREEN, 1);
form = new Form("Throw Exception");
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 (MIDletStateChangeException exception)
{
exitFlag = true;
}
}
}
}

Throwing a MIDletStateChangeException

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class ThrowException extends MIDlet
implements CommandListener
{
private Display display;
private Form form;
private Command exit;
private boolean isSafeToQuit;
public ThrowException()
{
isSafeToQuit = false;
display = Display.getDisplay(this);
exit = new Command("Exit", Command.SCREEN, 1);
form = new Form("Throw Exception");
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)
{
StringItem msg = new StringItem (
"Busy", "Please try again.");
form.append(msg);
destroyApp(false);
}
else
{
destroyApp(true);
notifyDestroyed();
}
}
catch (MIDletStateChangeException exception)
{
isSafeToQuit = true;
}
}
}
}

Item Listener

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class RadioButtons extends MIDlet
implements ItemStateListener, CommandListener
{
private Display display;
private Form form;
private Command exit;
private Item selection;
private ChoiceGroup radioButtons;
private int defaultIndex;
private int radioButtonsIndex;
public RadioButtons()
{
display = Display.getDisplay(this);
radioButtons = new ChoiceGroup(
"Select Your Color",
Choice.EXCLUSIVE);
radioButtons.append("Red", null);
radioButtons.append("White", null);
radioButtons.append("Blue", null);
radioButtons.append("Green", null);
defaultIndex = radioButtons.append("All", null);
radioButtons.setSelectedIndex(defaultIndex, true);
exit = new Command("Exit", Command.EXIT, 1);
form = new Form("");
radioButtonsIndex = form.append(radioButtons);
form.addCommand(exit);
form.setCommandListener(this);
form.setItemStateListener(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();
}
}
public void itemStateChanged(Item item)
{
if (item == radioButtons)
{
StringItem msg = new StringItem(Your color is ",
radioButtons.getString(radioButtons.getSelectedIndex()));
form.append(msg);
}
}
}

Determining the Color Attribute of a Device

1. Create references.
2. Create a Display object.
3. Create an instance of the Command class to exit the MIDlet.
4. Call isColor() method.
5. Evaluate the return value of isColor() method.
6. Create an instance of the TextBox class that describes results of isColor()
method.
7. Associate the instances of the Command class with the instances of the
TextBox class.
8. Associate a CommandListener with the instance of the TextBox class.
9. Display the instance of the TextBox class on the screen.
10. Terminate the MIDlet when the Exit command is entered.




import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class CheckColor extends MIDlet implements CommandListener
private Display display;
private Form form;
private TextBox textbox;
private Command exit;
public CheckColor()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.SCREEN, 1);
String message=null;
if (display.isColor())
{
message="Color display.";
}
else
{
message="No color display";
}
textbox = new TextBox("Check Colors", message, 17, 0);
textbox.addCommand(exit);
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 == exit)
{
destroyApp(true);
notifyDestroyed();
}
}
}

Hello World J2ME Style

package greeting;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class HelloWorld extends MIDlet implements CommandListener
{
private Display display ;
private TextBox textBox ;
private Command quitCommand;
public void startApp()
{
display = Display.getDisplay(this);
quitCommand = new Command("Quit", Command.SCREEN, 1);
textBox = new TextBox("Hello World", "My first MIDlet", 40, 0);
textBox .addCommand(quitCommand);
textBox .setCommandListener(this);
display .setCurrent(textBox );
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command choice, Displayable displayable)
{
if (choice == quitCommand)
{
destroyApp(false);
notifyDestroyed();
}
}
}

file manager j2me sorce code download

file manager j2me sorce code download


import java.io.*;
import javax.microedition.io.file.FileSystemListener;
import javax.microedition.io.file.FileSystemRegistry;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import java.util.*;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;



public class FileManagerMidlet extends MIDlet implements FileSystemListener{
    private Display display;
    private FileManager manager;
    private SysRootsList rootsList;
    private DirList dirList;
    private CreateForm createForm;
    private PropertyForm propertyForm;
    private ReaderBox readerBox;
    private Alert errAlert;
    private Alert processAlert;
    private String copyFile = "";

    public FileManagerMidlet(){
        manager = new FileManager();
        FileSystemRegistry.addFileSystemListener(this);
    }

    public void startApp() {
        display = Display.getDisplay(this);
        try{
            if(rootsList == null){
                rootsList = new SysRootsList(this,manager.list());
            }
            display.setCurrent(rootsList);
        }catch(IOException ioe){
            showError("error!"+ioe.toString(),rootsList);
        }
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
        manager.release();
    }

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

   
    public void displayDirList(String dir) throws IOException{
        manager.changeDirectory(manager.getName(dir));
        if(manager.isDriverRoot()){
            display.setCurrent(rootsList);
        }else{
            String[] files = manager.list();
            if(dirList == null){
                dirList = new DirList(this);
            }
            dirList.update(manager.getCurrDir(),files);
            display.setCurrent(dirList);
        }
    }

   
    public void delete(String fileName){
        try{
            manager.delete(fileName);
            String[] files = manager.list();
            dirList.update(manager.getCurrDir(),files);
            display.setCurrent(dirList);
        }catch(IOException ioe){
            showError("error\n"+ioe.toString(),dirList);
        }
    }

   
    public void displayCreateForm(){
        if(createForm == null){
            createForm = new CreateForm(this);
        }
        createForm.setBackScreen(dirList);
        display.setCurrent(createForm);
    }


    public void displayPropertyForm(String f,Displayable backScreen){
        try{
            File file = manager.getProperty(f);
            if(propertyForm == null){
                propertyForm = new PropertyForm(this);
            }
            propertyForm.update(file,backScreen);
            display.setCurrent(propertyForm);
        }catch(IOException ioe){
            showError("error\n"+ioe.toString(),backScreen);
        }
    }

 
    public void showError(String errMsg,Displayable nextScreen){
        if(errAlert == null){
            errAlert = new Alert("error",errMsg,null,AlertType.ERROR);
            errAlert.setTimeout(Alert.FOREVER);
        }
        errAlert.setString(errMsg);
        display.setCurrent(errAlert,nextScreen);
    }

   
    public void showProcessInfo(String msg){
        if(processAlert == null){
            processAlert = new Alert("error..");
            Gauge gauge = new Gauge(null,false,100,1);
            processAlert.setIndicator(gauge);
            processAlert.setTimeout(100000);
        }
        processAlert.setString(msg);
        display.setCurrent(processAlert);
    }

 
    public void backTo(Displayable backScreen){
        display.setCurrent(backScreen);
    }

  
    public void create(File file){
        try{
            manager.create(file);
            String[] files = manager.list();
            dirList.update(manager.getCurrDir(),files);
            display.setCurrent(dirList);
        }catch(IOException ioe){
            showError("error"+ ioe.toString(),dirList);
        }
    }

    public void rootChanged(int state,java.lang.String rootName){
        Alert alert = new Alert("Root changed","",null,AlertType.INFO);
        if(state == FileSystemListener.ROOT_ADDED){
            alert.setString("root Added: "+rootName);
        }else if(state == FileSystemListener.ROOT_REMOVED){
            alert.setString("Root removed: "+rootName+".");
        }
        alert.setTimeout(2000);
        String[] sr = manager.getSysRoots();
        rootsList.update(sr);
        display.setCurrent(alert);
    }

   
    public void copy(String fileName){
        copyFile = manager.getCurrDir() + fileName;
    }

   
    public void paste() throws IOException{
        String desFile = manager.getName(copyFile);
        manager.copy(copyFile,desFile);
        String[] files = manager.list();
        dirList.update(manager.getCurrDir(),files);
        display.setCurrent(dirList);
    }

   
    public void openTextFile(String fileName,Displayable backScreen) throws IOException{
        if(!fileName.endsWith(".txt")){
            throw new IOException("error");
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        manager.read(fileName,baos);

      

        String fileContent = new String(baos.toByteArray(),"UTF-8");
        System.out.println(fileContent);
        if(readerBox == null){
            readerBox = new ReaderBox(this);
        }
        readerBox.setContent(fileName,fileContent);
        readerBox.setBackScreen(backScreen);
        display.setCurrent(readerBox);
    }

private class FileManager {
    public final String DRIVER_ROOT = "/";
    private final String URL_HEAD = "file://";
    public  final String PARENT_DIR = "..";

    private  String strSep = "/";
    private char chSep = '/';
    private String currDir;
    private FileConnection fconn;
    private Vector sysRoots;

  
    public FileManager(){
        currDir = DRIVER_ROOT;
        sysRoots = createSysRoots();
    }

   
    public Vector createSysRoots(){
        Enumeration e = null;
        e = FileSystemRegistry.listRoots();
        Vector v = new Vector();
        String rootName = null;
        while(e.hasMoreElements()){
            rootName = (String)e.nextElement();
            v.addElement(rootName);
        }
        return v;
    }

   
    private Vector getCurrDirFiles() throws IOException{
        if(currDir == DRIVER_ROOT){
            return sysRoots;
        }
       
        Enumeration e = null;
        e = fconn.list();
        String fileName;
        Vector v = new Vector();
        v.addElement(PARENT_DIR);
        while(e.hasMoreElements()){
            fileName = (String)e.nextElement();
            v.addElement(fileName);
        }
        return v;
    }

   
    public String[] list() throws IOException{
        Vector v = getCurrDirFiles();
        String[] fileArray = new String[v.size()];
        v.copyInto(fileArray);
        return fileArray;
    }

   
    public String[] getSysRoots(){
        sysRoots = createSysRoots();
        String[] r = new String[sysRoots.size()];
        sysRoots.copyInto(r);
        return r;
    }

   
    public void create(File file) throws IOException{
        if(currDir==DRIVER_ROOT){
            throw new IOException("dir:"+file);
        }
        String fileUrl = URL_HEAD+currDir+file.getName();
        FileConnection fc = (FileConnection)Connector.open(fileUrl);
        if(fc.exists()){
            throw new IOException("file connection");
        }

       
        if(file.isDirectory()){
            fc.mkdir();
        }else{
            fc.create();
        }
        fc.setReadable(file.canRead());
        fc.setWritable(file.canWrite());
        fc.setHidden(file.isHidden());

        fc.close();
    }

   
    public void delete (String fileName) throws IOException{
        if(currDir == DRIVER_ROOT){
            throw new IOException("sds:"+fileName);
        }

        String fileUrl = URL_HEAD+currDir+fileName;
        FileConnection fc = (FileConnection)Connector.open(fileUrl);
        if(!fc.canWrite()){
            throw new IOException("sds: "+fileName+" sdds");
        }
        if(fc.isDirectory()){
            Enumeration e = fc.list();
            if(e.hasMoreElements()){
                throw new IOException("sds:"+fileName);
            }
        }
        fc.delete();
        fc.close();
    }

  
    public File getProperty(String fileName)throws IOException{
        File f = new File(fileName);
        String fileUrl = URL_HEAD+currDir+fileName;
        FileConnection fc = (FileConnection)Connector.open(fileUrl);
        f.setReadable(fc.canRead());
        f.setWritable(fc.canWrite());
        f.setHidden(fc.isHidden());
        f.setLastModify(fc.lastModified());
        fc.close();
        return f;
    }

   
    public void copy(String srcFile,String newFileName)throws IOException{
        String srcFileUrl = URL_HEAD+srcFile;
        System.out.println("src:"+srcFileUrl);
        FileConnection srcFc = (FileConnection)Connector.open(srcFileUrl);

        if(!srcFc.exists()||!srcFc.canRead()){
            throw new IOException("sd:\""+srcFile+"\"ds");
        }
        if(srcFc.isDirectory()){
            throw new IOException("sd:\""+srcFile+"\"eeer");
        }
        if(currDir == DRIVER_ROOT){
            throw new IOException("errrrrrr");
        }

        String desFileUrl = URL_HEAD+currDir+newFileName;
        System.out.println("des: "+desFileUrl);
        FileConnection desFc = (FileConnection)Connector.open(desFileUrl);
        if(desFc.exists()){
            throw new IOException("errrrrrrrr");
        }

       
        desFc.create();
        InputStream is = srcFc.openInputStream();
        OutputStream os = desFc.openOutputStream();
        byte[] buf = new byte[200];
        int n = -1;
        while((n = is.read(buf,0,buf.length))!= -1){
            os.write(buf, 0, n);
        }
        is.close();
        os.close();
        srcFc.close();
        desFc.close();
    }

   
    public void changeDirectory(String dirName)throws IOException{
        if(dirName==PARENT_DIR){
            if(currDir==DRIVER_ROOT){
            }else{
                if(manager.getPath(currDir).equals(DRIVER_ROOT)){
                    currDir = DRIVER_ROOT;
                    fconn.close();
                    fconn = null;
                }else{
                    fconn.setFileConnection(PARENT_DIR);
                    currDir = manager.getPath(currDir);
                }
            }
        }else{
            if(currDir==DRIVER_ROOT){
                currDir = currDir+dirName;
                String dirUrl = URL_HEAD+ currDir;
                fconn = (FileConnection)Connector.open(dirUrl);
            }else{
                currDir = currDir+dirName;
                fconn.setFileConnection(dirName);
            }
        }
    }

   
    public String getCurrDir(){
        return currDir;
    }

   
    public void release(){
        try{
            if(fconn!=null){
                fconn.close();
            }
        }catch(IOException ioe){

        }
    }

   
    public String getName(String pathName){
        int index = pathName.lastIndexOf(chSep,pathName.length()-2);
        String name = pathName;
        if(index != -1){
            name = pathName.substring(index+1);
        }
        return name;
    }

    public String getPath(String pathName){
        int index = pathName.lastIndexOf(chSep,pathName.length()-2);
        String path = "";
        if(index != -1){
            path = pathName.substring(0,index+1);
        }
        return path;
    }

    public boolean isDirectory(String dir){
        return dir.endsWith(strSep)||dir.endsWith(PARENT_DIR);
    }

   
    public boolean isDriverRoot(){
        return currDir.equals(DRIVER_ROOT);
    }

 
    public long read(String file,ByteArrayOutputStream baos)throws IOException{
        String fileUrl = URL_HEAD+currDir+file;
        FileConnection fc = (FileConnection)Connector.open(fileUrl);
        if(!fc.exists()){
            throw new IOException("er:\""+file+"\"e");
        }
        if(fc.isDirectory()){
            throw new IOException("re:\n"+file+"e");
        }
        if(!fc.canRead()){
            throw new IOException("er: "+file+" er");
        }

        InputStream is = fc.openInputStream();
        int n = -1;
        int total = 0;
        byte[] buf = new byte[250];
        while((n = is.read(buf, 0, buf.length))!=-1){
            baos.write(buf, 0, n);
            total+=n;
        }
        is.close();
        fc.close();

        return total;
    }
}
private class DirList extends List implements CommandListener{
    private FileManagerMidlet midlet;
    private Image imgFile;
    private Image imgDir;

    private Command cmdExit = new Command("Exit",Command.EXIT,1);
    private Command cmdOk = new Command("Ok",Command.OK,2);
    private Command cmdDelete = new Command("Delete",Command.SCREEN,3);
    private Command cmdCreate = new Command("Create",Command.SCREEN,3);
    private Command cmdProperty = new Command("Property",Command.SCREEN,3);
    private Command cmdCopy = new Command("Copy",Command.SCREEN,3);
    private Command cmdPaste = new Command("Paste",Command.SCREEN,3);
    private String[] files;
    private String dir;

    public DirList(FileManagerMidlet midlet){
        super(null,IMPLICIT);
        this.midlet = midlet;
        try{
            imgFile = Image.createImage("/file.png");
            imgDir = Image.createImage("/dir.png");
        }catch(IOException ioe){

        }

        addCommand(cmdExit);
        addCommand(cmdOk);
        addCommand(cmdDelete);
        addCommand(cmdCreate);
        addCommand(cmdProperty);
        addCommand(cmdCopy);
        addCommand(cmdPaste);
        setCommandListener(this);
    }

    public void update(String dir,String[] files){
        this.dir = dir;
        setTitle(dir);
        deleteAll();
        this.files = files;
        for(int i = 0;i<files.length;i++){
            if(manager.isDirectory(files[i])){
                append(files[i],imgDir);
            }else{
                append(files[i],imgFile);
            }
        }
    }

    public void commandAction(Command cmd,Displayable d){
        if(cmd==cmdExit){
            midlet.exit();
        }else if(cmd == cmdOk){
            Thread t = new Thread(){
                public void run(){
                    int index = getSelectedIndex();
                    try{
                        if(manager.isDirectory(files[index])){
                            midlet.displayDirList(files[index]);
                        }else{
                            midlet.openTextFile(files[index], DirList.this);
                        }
                    }catch(IOException ioe){
                        midlet.showError(ioe.toString(), DirList.this);
                    }
                }
            };
            t.start();
        }else if(cmd == cmdDelete){
            Thread t = new Thread(){
              public void run(){
                  int index = getSelectedIndex();
                  midlet.delete(files[index]);
              }
            };
            t.start();
        }else if(cmd == cmdCreate){
            midlet.displayCreateForm();
        }else if(cmd == cmdProperty){
            Thread t = new Thread(){
                public void run(){
                    int index = getSelectedIndex();
                    System.out.println(files[index]);
                    midlet.displayPropertyForm(getString(index), DirList.this);
                }
            };
            t.start();
        }else if(cmd == cmdCopy){
            int index = getSelectedIndex();
            midlet.copy(files[index]);
        }else if(cmd== cmdPaste){
            Thread t =new Thread(){
                public void run(){
                    try{
                        midlet.paste();
                    }catch(IOException ioe){
                        midlet.showError(":\n"+ioe.toString(), DirList.this);
                    }
                }
            };
            t.start();
        }
    }
}
public class CreateForm extends Form implements CommandListener{
    private FileManagerMidlet midlet;
    private TextField tfFileName;
    private ChoiceGroup cgType;
    private String[] typeName = {"File","Folder"};
    private ChoiceGroup cgProperty;
    private String[] propertyName = {"Readable","Writable","Hidden"};

    private Command cmdBack = new Command("Back",Command.BACK,1);
    private Command cmdCreate = new Command("Create",Command.SCREEN,2);
    private Displayable backScreen;

    public CreateForm(FileManagerMidlet midlet){
        super("");
        this.midlet = midlet;
        tfFileName = new TextField("File name: ","",30,TextField.ANY);
        append(tfFileName);

        cgType = new ChoiceGroup("Type:",Choice.EXCLUSIVE);
        for(int i=0;i<typeName.length;i++){
            cgType.append(typeName[i], null);
        }
        append(cgType);

        cgProperty = new ChoiceGroup("Property",Choice.MULTIPLE);
        for(int i=0;i<propertyName.length;i++){
            cgProperty.append(propertyName[i], null);
        }
        append(cgProperty);

        addCommand(cmdBack);
        addCommand(cmdCreate);
        setCommandListener(this);
    }

    public void setBackScreen(Displayable backScreen){
        this.backScreen = backScreen;
    }

    public void commandAction(Command cmd,Displayable d){
        if(cmd==cmdCreate){
            midlet.showProcessInfo("........");
            Thread t = new Thread(){
                public void run(){
                    String name = tfFileName.getString();
                    if(name.endsWith("/")){
                        midlet.showError("", CreateForm.this);
                        return;
                    }
                    int index = cgType.getSelectedIndex();
                    if(index==1){
                        name +="/";
                    }
                    boolean[] shux = new boolean[3];
                    cgProperty.getSelectedFlags(shux);

                    File f = new File(name);
                    f.setReadable(shux[0]);
                    f.setWritable(shux[1]);
                    f.setHidden(shux[2]);
                    midlet.create(f);
                }
            };
            t.start();
        }else if(cmd == cmdBack){
            midlet.backTo(backScreen);
        }
    }
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 *
 */
public class File {
    private String name;
    private boolean readable;
    private boolean writable;
    private boolean hidden;
    private long modifyDate;

    public File(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

    public boolean isDirectory(){
        return name.endsWith("/");
    }

    public boolean canRead(){
        return readable;
    }

    public void setReadable(boolean b){
        readable = b;
    }

    public boolean canWrite(){
        return writable;
    }

    public void setWritable(boolean b){
        writable = b;
    }

    public boolean isHidden(){
        return hidden;
    }

    public void setHidden(boolean b){
        hidden = b;
    }

    public long getLastModify(){
        return modifyDate;
    }

    public void setLastModify(long l){
        modifyDate = l;
    }
}
public class PropertyForm extends Form implements CommandListener{
    private FileManagerMidlet midlet;
    private StringItem siName;
    private StringItem siReadable;
    private StringItem siWritable;
    private StringItem siHidden;
    private StringItem siModifyDate;

    private Displayable backScreen;
    private Command cmdBack = new Command("Back",Command.BACK,1);

    public PropertyForm(FileManagerMidlet midlet){
       
        super("");
        this.midlet = midlet;
        siName = new StringItem("Name:","");
        siReadable = new StringItem("Readable","");
        siWritable = new StringItem("Writable","");
        siHidden = new StringItem("Hidden","");
        siModifyDate = new StringItem("ModifyDate","");
        append(siName);
        append(siReadable);
        append(siWritable);
        append(siHidden);
        append(siModifyDate);
        addCommand(cmdBack);
        setCommandListener(this);
    }

    public void update(File f,Displayable backScreen){
        this.backScreen = backScreen;
        siName.setText(f.getName());

        if(f.canRead()){
            siReadable.setText("Yes");
        }else{
            siReadable.setText("No");
        }

        if(f.canWrite()){
            siWritable.setText("Yes");
        }else{
            siWritable.setText("No");
        }

        if(f.isHidden()){
            siHidden.setText("Yes");
        }else{
            siHidden.setText("No");
        }

        long d = f.getLastModify();
        Calendar cale = Calendar.getInstance();
        cale.setTime(new Date(d));
        String t = cale.get(Calendar.YEAR)+"Year"
                +(cale.get(Calendar.MONTH)+1)+"Month"
                +cale.get(Calendar.DAY_OF_MONTH)+"Day"
                +cale.get(Calendar.HOUR_OF_DAY)+"Hour"
                +cale.get(Calendar.MINUTE)+"Minute";
        siModifyDate.setText(t);
    }

    public void commandAction(Command cmd,Displayable d){
        if(cmd==cmdBack){
            System.out.println("OK"+midlet);
            Display display = Display.getDisplay(midlet);
            display.setCurrent(backScreen);
        }
    }
}
public class ReaderBox extends TextBox implements CommandListener{
    private FileManagerMidlet midlet;
    private Command cmdBack = new Command("Back",Command.BACK,1);
    private Displayable backScreen;

    public ReaderBox(FileManagerMidlet midlet){
        super("","",2000,TextField.ANY|TextField.UNEDITABLE);
        this.midlet =midlet;
        addCommand(cmdBack);
        setCommandListener(this);
    }

    public void setContent(String fileName,String content){
        setTitle("File:"+fileName);
        setMaxSize(content.length());
        setString(content);
    }

    public void setBackScreen(Displayable d){
        this.backScreen = d;
    }

    public void commandAction(Command cmd,Displayable d){
        if(cmd==cmdBack){
            midlet.backTo(backScreen);
        }
    }
}
public class SysRootsList extends List implements CommandListener{
    private FileManagerMidlet midlet;
    private Command cmdExit = new Command("Exit",Command.EXIT,1);
    private Command cmdSelect = new Command("Select",Command.ITEM,2);
    private Image img;
    private String[] roots;

    public SysRootsList(FileManagerMidlet midlet,String[] roots){
        super("/",IMPLICIT);
        this.midlet = midlet;
        try{
            img = Image.createImage("/derive.png");
        }catch(IOException ioe){
        }
        update(roots);
        addCommand(cmdExit);
        addCommand(cmdSelect);
        setCommandListener(this);
    }

  
    public void show(){
        Display display = Display.getDisplay(midlet);
        display.setCurrent(this);
    }

 
    public void update(String[] roots){
        this.roots = roots;
        deleteAll();
        for(int i=0;i<roots.length;i++){
            append(roots[i],img);
        }
    }

    public void commandAction(Command cmd,Displayable d){
        if(cmd == cmdExit){
            midlet.exit();
        }else if(cmd== cmdSelect){
            Thread t = new Thread(){
                public void run(){
                    try{
                        int index = getSelectedIndex();
                        midlet.displayDirList(roots[index]);
                    }catch(IOException ioe){
                        midlet.showError(ioe.toString(), SysRootsList.this);
                    }
                }
            };
            t.start();
        }
    }
}

}