1 / 51

บทที่ 3 Java Wireless Toolkit (2)

บทที่ 3 Java Wireless Toolkit (2). วิชา 322252 Advance Programming in JAVA อ.วชิราวุธ ธรรมวิเศษ ภาควิชาวิทยาการคอมพิวเตอร์ คณะวิทยาศาสตร์ มหาวิทยาลัยขอนแก่น. Learning Objectives. After this lecture, you will learn: Basic principals of MIDlet programming Overview of MIDlet APIs

carlow
Download Presentation

บทที่ 3 Java Wireless Toolkit (2)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. บทที่ 3 Java Wireless Toolkit (2) วิชา 322252 Advance Programming in JAVA อ.วชิราวุธ ธรรมวิเศษ ภาควิชาวิทยาการคอมพิวเตอร์ คณะวิทยาศาสตร์ มหาวิทยาลัยขอนแก่น

  2. Learning Objectives After this lecture, you will learn: • Basic principals of MIDlet programming • Overview of MIDlet APIs • Contrast MIDlet APIs v.s. J2SE APIs • MIDlet basic GUI programming • MIDlet Forms and Lists

  3. Section I MIDlet APIs

  4. MIDP Packages: An overview Similar to all other Java-based packages. MIDP package consists of TWO major components: • Core (standard) MIDP packages, including- java.lang (MID Profile Language Classes included from J2SE)- java.io (Provides for system input and output through data streams)- java.util (MID Profile Utility Classes included from J2SE) Midlet API

  5. MIDP Packages: An overview (cont.) • Extended (specific) MIDP packages, including: • Application Lifecycle Package:javax.microedition.midlet • Package that defines Mobile Information Device Profile applications and the interactions between the application and the environment in which the application runs) • Persistent Package:javax.microedition.rms • Include APIs that provide a mechanism for MIDlets to persistently store data and later retrieve it • User Interface Package: javax.microedition.lcdui • GUI APIs that provides a set of features for implementation of user interfaces for MIDP applications • Networking Package:javax.microedition.io • This includes networking support based on the GenericConnection framework from the Connected Limited Device Configuration.

  6. Main features of core J2ME APIs – java.lang • Main features of J2ME java.lang package • MIDP does NOT support Double and Floating point calculations, it's understandable as complex floating point calculation required substantial memory and processing time which are all unfavorable for mobile devices. • Both String and StringBuffer are still appeared CLDC java.lang package. In the earlier version of MIDP, valueOf() is not supported in java.lang. However, in the latest MIDP specification, various implementation of valueOf() methods can be found. • No user classloading • owing to the resource limitation, CLDC/MIDP does not allow users to define their own classloaders. • The application manager that runs MIDlets has a classloader, but you cannot access it or use in your own way. • Object Finalization is not supported in MIDP • That is, to clean up resources, you need to do it explicitly instead of using finalize(). • In a small MIDP device, it is good to do that as to remind developers to clean up unnecessary on their own to reserve the memory consumption ofthe mobile device.

  7. Main features of core J2ME APIs – java.lang (cont.) • Main features of J2ME java.lang package • Native methods are NOT supported as well. • Runtime • Runtime is an important class to provide access to the JVM. In CLDC/MIDP, only a minimum (and the core) methods are remained. • One important note is that Runtime does not support running external processes using exec() method. It makes sense in order not to complicate the tiny system. • System • System provides basic access to the system-wide resources. • Similar to Runtime, only the most critical methods are left behind. • It is interesting to note that System.in is NOT supported in MIDP. It makes sense, as SystemIn stands for console input, in a MIDP device, there is no console concept at all! 

  8. Main features of core J2ME APIs – java.io • Main features of J2ME java.io package • Similarly, the java.io package in the CDLC/MIDP world is the stripped down version of java.io in J2SE. • Although many methods are missing in the CLDC/MIDP world, however all the "major" methods are still there, including: • DataInput/Output() • DataInput(Output)Stream() • Input(Output)Stream() • Reader() • Writer() which provide sufficient methods for MIDlet applications.

  9. Main features of core J2ME APIs – java.io (cont.) • As compared with J2SE, there are some main features being found in java.io package: • MIDP does NOT support local file system, that's why ALL the file-related methods are disappeared. The reason behind is: MIDP using other concept to save data in a MIDP device - so called "Record Stores", which is implemented in the javax.microedition.rms package. • It is not difficult to find out that most of the "complex" utility stream classes, including object-related stream classes such as ObjectInput/OutputStream(), String-related stream classes such as StringReader/Writer(). These methods are not implemented mainly due the limited capacity of the tiny mobile devices. • However, the "core" and "basic" java.io are still there, including the DataInput/OutputStream(). These are all good enough to implement the MIDlets. • Although MIDP device expect "simple" mobile application. However, it MUST allow user to implement multi-language application (e.g. Chinese, Japanese, etc), which is in needed of Unicode character implementation scheme. So, in order to suit for this requirement, MIDP (like J2SE), allow user to make use of InputStreamReader and OutputStreamWriter() to handle these kind of byte-stream to charater-streams unicode conversions. 

  10. Main features of core J2ME APIs – java.util • Main features of J2ME java.util package • As predicted, most java.util package methods are NOT supported in CLDC/MIDP, mainly because most implementation found in java.util package are related to "complex" object manipulations, such as LinkedList, Set, Array, ArrayLists, which are hardly and difficult to be handled in the mobile device.  • However, some comparatively "simple" implementation can be found in CLDC/MIDP java.util package, including: Enumeration & Hashtable. • Date is an important element in mobile device applications, so it is implemented in java.util package. Similarly, TimeZone() can also be found in the CLDC/MIDP APIs to represent the time zone identification (which is New in JDK 1.3) • Similar to WAP programming, Timer is a vital element in mobile applications. So, MIDP also implements Timer() and TimerTask() to perform that kind of tasks. • Below is a summary of the Timer-related methods which are being used in MIDP (and is NEW in JDK 1.3). They include:- Timer()- TimerTask()- TimeZone()

  11. Section II MIDlet GUI Programming

  12. MIDlet GUI: Abstraction vs. Discovery Owing to the wide range of MIDs in term of GUI. MIDP comes up with TWO new ideas to specify a GUI in any MIDs: Abstraction & Discovery: Abstraction • It specifies a GUI in abstract terms • Relying on the MIDP implementation to create something concrete. • For example, instead of saying "Display the word 'Next' on the screen above the right-soft button", one will says "Give me a Next command somewhere in this GUI". Discovery • It concerns with the MIDlet that learnt about the device at runtime and tailors the GUI programmatically. • For example, one might find out how big the device's screen is in order to scale the GUI appropriate Note: • Although MIDP supports both concepts. Abstraction is more preferable as it involves less code in MIDlets and it only involves more works on the MIDP implementation.   • However, in some specific applications (e.g. game applications), one might be more concern in the "exploring" the actual size of the MID screen to provide a better GUI application. In this case, Discovery concept is adopted. • Nevertheless, MIDP's GUI APIs are designed so that it is easy to mix the two techniques in the same MIDlet.

  13. The Displayable class: core MIDlet GUI class • MIDP implements all the UI-related classes with its javax.microedition.lcdui package. Although it contains a group of classes, there is ONE fundamental class - so called Displayable - which is the "core" of MIDlet GUI display. • In short, the MID's display is represented by an instance of the Display class - accessed from the factory method "getDisplay()". • The main purpose of Display class is to keep track of what is currently displayed onto the MID, which is return as an instance of the Displayable object. • In particular, MIDlets can change the contents of the display by passing Displayable objects to the setCurrent() method. The following depicts the typical life-cycle of the GUI handling scheme:

  14. The Displayable class: core MIDlet GUI class (cont.) • Life-cycle of MIDlet GUI interactions

  15. The Displayable class: core MIDlet GUI class (cont.) • The Displayed class mainly consists of TWO sub-classes: Screen and Canvas. • Screen contains all the "basic" UIs in building MIDlets, including textboxes, lists and forms. These forms an important basis to build a wide range of mobile commerce applications, especially the form-driven EC applications we have implemented in most EC sites.  • Canvas contains all the related classes to build a more UI demanding MIDlets (e.g. MIDlet games). It provides a wide range of methods for writing applications that need to handle low-level events and to issue graphics calls for drawing to the MID displays.  • In this course, we will focus on how to implement the Screen-related object classes - the essential part to build m-commerce applications.  • First of all, let's discuss how to implement the basic display objects: Alerts and Textboxes. • In the next section, we will move on Lists and Forms.

  16. The Displayable class: core MIDlet GUI class (cont.) • Family tree of the Displayable class

  17. Your First MIDlet GUI program: SimpleTextBox • SimpleTextBox is a truely simple MIDlet that will do the following: • Display a simple Textbox with Title "Simple Text Box" and display a message "Write something now!". • Place a command button "Exit" onto the display. • In SimpleTextBox, our MIDlet contain a single command called "Exit". • In the next example, we try to add THREE more commands, namely: • Help • About • Go to see what happen - MultiCommands.

  18. Your First MIDlet GUI program: SimpleTextBox Simple_Text_Box.java import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class SimpleTextBox extends MIDlet { public void startApp() { Displayable d = new TextBox("Simple Text Box", "Write something now!", 20, 0); Command c = new Command("Exit", Command.EXIT, 0); d.addCommand(c); d.setCommandListener(new CommandListener() { public void commandAction(Command c, Displayable s) { notifyDestroyed(); } }); Display.getDisplay(this).setCurrent(d); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} }

  19. One Step Further: Multiple Commands • MultiCommands.java import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class MultiCommands extends MIDlet { private Command mExit, mAbout, mHelp, mGo; public MultiCommands(){ mExit = new Command("Exit", Command.EXIT, 0); mAbout = new Command("About", Command.SCREEN, 1); mHelp = new Command("Help", Command.SCREEN, 1); mGo = new Command("Go", Command.SCREEN, 1); } public void startApp() { Displayable d = new TextBox("Simple Text Box", "Write something now!", 20, 0); d.addCommand(mExit); d.addCommand(mAbout); d.addCommand(mHelp); d.addCommand(mGo);

  20. One Step Further: Multiple Commands d.setCommandListener(new CommandListener() { public void commandAction(Command c, Displayable s) { if (c == mExit) notifyDestroyed(); else if (c == mAbout) System.out.println("About ..."); else if (c == mHelp) System.out.println("Help ..."); else if (c == mGo) System.out.println("Go ..."); } }); Display.getDisplay(this).setCurrent(d); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} }

  21. Titles and Tickers • So far we have not formally explained or defined what is a Screen object. • As defined by Sun : • Screen is the common superclass of all high-level user interface classes. Adds optional title and ticker-tape output to the Displayable class. The contents displayed and their interaction with the user are defined by subclasses. • In a simple term, Screen is the "desktop" object through that we "put" all the GUI objects onto it.  • Anyway, one important point is that. For every Screen object, it has a Title and a Ticker.  • Title is a string that appears at the top of the screen, as you can see it in our previous example. The syntax to create(access) a Title:        public void setTitle(String newTitle)        public String getTitle() • Ticker is simply a string of text that scrolls across the top of the Screen object (named after the traditional stock tickers). The syntax to create(access) a Ticker:        public void setTicker(Ticker newTicker)        public Ticker getTicker() • We can extend the SimpleTextBox to create a Ticker (t) as follows.

  22. Titles & Tickers (cont.) ScreenAndTicker.java import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class ScreenAndTicker extends MIDlet implements CommandListener { private static final String TICKER_TEXT = "Can you see this ticker text, ..............." + "It will go on and on and on ....!"; private Display display; private TextBox tbox; public ScreenAndTicker() { display = Display.getDisplay(this); tbox = new TextBox("Ticker", "Write something now!", 20, 0); Command c = new Command("Exit", Command.EXIT, 0); tbox.addCommand(c); Ticker t = new Ticker(TICKER_TEXT); tbox.setTicker(t); }

  23. Titles & Tickers (cont.) public void startApp() { display.setCurrent(tbox); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable s) { notifyDestroyed(); } }

  24. Alerts • An alert is a informative message shown to the user, with information defined by the user.  • In MIDP implementation, there are TWO kinds of alert: • Timed Alert:- Alert which is shown for a certain period of time. - It is used to display message that does NOT need user acknowledgment.- A simple warning: "Your address book is FULL!“ • Modal Alert- Like a Modal Dialog box in Window programming. Modal alert will stays up until the user dismisses it. - It is useful when a list of choices are offered to user to that action.- E.g. Give user to choose between GO or Escape.  • Note that one can associate sound or image together with alerts. • The formal syntax for declaring alerts: public Alert()    public Alert(String title, String alerttext, Image alertImage, Alert Type alertType) Parameter:title - the title string, or null if there is no titlealertText - the string contents, or null if there is no stringalertImage - the image contents (in PNG format), or null if there is no image alertType - the type of the Alert, or null if the Alert has no specific type

  25. A Sample Alert: Alerts.java The following example Alerts.java will demonstrate the TWO types of alerts:  • mTimedAlert: • A Timed alert to display the Warning Message: Your Address Book is Full! • mModalAlert: • A Modal alert to display the About message. • To invoke these two alerts, TWO commands are used: A About command is used to invoke the mModalAlert and the GO command is used to invoke the mTimedAlert. • The following shows the source program and the snapshot screen. • Note the difference performances of these two alerts in the following example.

  26. Alerts.java (cont.) • Alerts.java import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class Alerts extends MIDlet implements CommandListener { private Display mDisplay; private TextBox mTextBox; private Alert mTimedAlert; private Alert mModalAlert; private Command mAboutCommand, mGoCommand, mExitCommand; public Alerts() { mAboutCommand = new Command("About", Command.SCREEN, 1); mGoCommand = new Command("Go", Command.SCREEN, 1); mExitCommand = new Command("Exit", Command.EXIT, 2); }

  27. Alerts.java (cont.) public void startApp() { mDisplay = Display.getDisplay(this); mTextBox = new TextBox("Alerts", " ", 1, TextField.ANY); mTextBox.addCommand(mAboutCommand); mTextBox.addCommand(mGoCommand); mTextBox.addCommand(mExitCommand); mTextBox.setCommandListener(this); mTimedAlert = new Alert("Warning!!!", "Your Address Book is FULL!!!", null, AlertType.INFO); mModalAlert = new Alert("About Alerts", "Alerts is a simple MIDlet that demonstrates the use of Alerts.", null, AlertType.INFO); mModalAlert.setTimeout(Alert.FOREVER); mDisplay.setCurrent(mTextBox); } Menu Screen

  28. Alerts.java (cont.) public void pauseApp() { } public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable s) { if (c == mAboutCommand) mDisplay.setCurrent(mModalAlert); else if (c == mGoCommand) mDisplay.setCurrent(mTimedAlert, mTextBox); else if (c == mExitCommand) notifyDestroyed(); } } NOTE: • By default, in a Timed Alert, MIDP uses a default timeout value. You can access it using the getDefaultTimeout() method. • To change the timeout period. You can use the setTimeout() method (the timeout value is defined in milliseconds)E.g.     alert.setTimeout(6000)   will set the timeout to SIX seconds. • You can also set the timeout to FOREVER, which means a Modal Alert.E.g.     alert.setTimeout(Alert.FOREVER) • So, try this for the above example. First, reset the timeout to SIX second, and then set it to FOREVER to see what happens! About Screen Modal Alert GO Screen Timed Alert

  29. Section III MIDlet Lists and Forms

  30. What is a MIDlet List? • MIDlet lists, just like the HTML list, provides an list of choices (called elements) for user to select. • A text string or an image is used to represent each element in the list. • List supports the selection of: • single element; • multiple selection. For implementation, there are THREE kinds of list: • IMPLICIT • where select causes immediate notification of the application if there is a CommandListener registered. - The element that has the focus will be selected before any CommandListener for this List is called. - An implicit SELECT_COMMAND is a parameter for the notification. • EXCLUSIVE • where select operation changes the selected element in the list. - only one element can be selected at a time, similar to the "radio button" in Window programming - Application is not notified. • MULTIPLE • where select operation toggles the selected state of the focused Element. - it allows multiple selections, similar to the "check boxes" in Window programming - Application is not notified

  31. MIDlet Lists: ListDemo Implicit List Exclusive List Multiple List

  32. How to create a List? • The basic syntax to create a list: public List (String title, int type) public List (String title, int type, String[] stringElements, Image[] imageElements) • The stringElements, if using, cannot be null. However, it can contain a null array elements.  • As discussed before, MIDP using PNG format to define image elements. try { // load the duke image to place in the image array Image duke = Image.createImage("/midp/uidemo/Icon.png"); // these are the images and strings for the choices. imageArray = new Image[]{ duke, duke, duke }; } catch(java.io.IOException err) { // ignor the image loading failure the application can recover. } • Similar to other MIDlet GUI elements, we can define more list elements than it can be displayed. As discussed previously, ALL MIDlet devices will have their own way to handle it. We don't need to worry about it. 

  33. How to invoke action in a IMPICIT List? • IMPLICIT list allow user to invoke action upon selection.  • MIDlet implements this by using commandAction() method of the List's CommandListener (a natural concept). • A special value is passed to the commandAction() as the Command parameter upon selection. Syntax as follows: public void commandAction (Command c, Displayable s) {        if  (c == nextCommand)            // do sth ....        else if (c == List.SELECT_COMMAND)            // do other ...        }

  34. How to edit a List? • MIDlet lists provide method for: • Adding • Removing • Appending • Accessing • list elements.  • To achieve this, each element in a list has an index. The first one with index 0. We can access a particular list element (based on its index) by using setElement(). To add new element on a particular "position", we can use insertElement. To append a new element at the end of the list by using appendElement().  • A complete syntax of all the core list-related methods are shown below: public void setElement      (int index, String stringElement, Image imageElement);        public void insertElement   (int index, String stringElement, Image imageElement);        public void appendElement (String stringElement, Image imageElement);        public void deleteElement   (int index);Note: See also APIs

  35. What is a MIDlet Form? • A MIDlet Form is a screen object that can include an arbitrary collection of user-interface controls - known as items. • In a typical mobile commerce application. You always have to provide e-form for user to fill in all the critical information. E.g. booking order system, library catalog query system, questionnaire collection systems, etc. Just like what you have learnt (or will be learnt) in HTML forms. • However, in MIDlet forms, you need to take care about the minimum screen size for a MID (which is 95 x 54 pixels). Although your MID will handle the oversize interface, it may "distort" the whole UI appearance! • To create a MIDlet form just calls the Form object: public Form (String title)        public Form (String title, Iterm [] items) • You can either just create the Form object first, or declare the Form items at the time.

  36. Basic MIDlet Form elements – StringItem & TextField • Similar to HTML Forms, MIDlet Forms implement the following items: • StringItem    - A simple text labelE.g.         StringItem     stringItem = new StringItem ("Name", "Raymond")     • will produce a text labe with "Raymond" as initial valueNote: • You can use getText(), getLabel(), setText() and setLabel() to access and reset the corresponding StringItem element. • TextField    - Editable string, just like text field in HTML formsE.g.     new TextField("Name", "Raymond Lee", 20, TextField.ANY)  - will produce a Text Box name "Name" and "Raymond Lee" as initial valueSyntax:    public TextField (String label, String text, int maxSize, int input_constraint)Note: TextFields can limit input with following values: ANY                    - Allows any input typesNUMERIC            - Restricts to numeric inputPHONENUMER    - Requires phone number inputEMAILADDR        - Requires email address inputURL                    - Requires URL inputPASSWORD       - Password input, entered characters will be displayed as *s

  37. Basic MIDlet Form elements - ImageItem • ImageItem    - Allows users to embed images into a form, which is represented by instances of ImageItem.ImageItems have the following attributes: • label        - label text for the image itemlayout      - the placement of the image, it can be LAYOUT_(LEFT/ CENTER/ RIGHT for horz. placement), • LAYOUT_(NEWLINE_BEFORE / NEWLINE_AFTER for vertical placement), or LAYOUT_DEFAULT for default placement.E.g.   • Image img = Image.createImage("/midp/uidemo/JavaPowered-8.png")  // Load the image first • ImageItem("Default Layout", img, ImageItem.LAYOUT_DEFAULT, "Image Cannot be shown")  // create the ImageItemThe following is a typical ImageItem which is using the DEFAULT layout placement.

  38. Basic MIDlet Form elements - DateField • DateField    - A useful and important form item for user to input Date-related information.User can enter input the date or time or both, MIDP will do the formatting for it.To create a DateField, first specify the DateField labe and the type. • Three different types are provided: • DATE    : displays an editable dataTIME    : displays an editable timeDATE_TIME: displays both date and time • To create a DateField, use the following syntax:        public DateField (String label, int mode)        public DateField (String label, int mode, TimeZone timeZone)The following shows all the DateField items and the corresponding editing GUI. Midlet API

  39. Basic MIDlet Form elements - DateField DATE Field Only TIME Field Only DATE_TIME together Editing Interface (Date) Editing Interface (Time) • Gauge

  40. Basic MIDlet Form elements - Gauge • Gauge    - A Gauge represents an integer value. It's up to the implementation to decide how to display itself on a MID.The value of the Gauge can be accessed and modified by using getValue() and setValue() methods. • This value is ranged from 0 to a maximum value (which can be manipulated by getMaxValue() and setMaxValue()). • The formal syntax to create a Gauge is:  public Gauge (String label, boolean interactive, int maxValue, int initialValue)For example: Gauge g = new Gauge ("Power", true, 24, 2)   is used to creates an interactive Gauge with a maximum value of 24 and an initial value of 2. 

  41. Basic MIDlet Form elements - ChoiceGroup • ChoiceGroup offers a list of choices for user to choose. It is very similar to MIDlet List which discussed previously. • In fact, both of them share and implement the same interface - the Choice interface - a generic interface for the provision of choice of items. • The constructors allowed for ChoiceGroup are: public ChoiceGroup (String label, int choiceType)         public ChoiceGroup (String label, int choiceType, String[] stringElements, Image[] imageElements) • Similar to MIDlet Lists, ChoiceGroup can be EXCLUSIVE, MULTIPLE or IMPLICIT. In fact, ChoiceGroup's constructors work exactly like List's constructors.  • In the next example, we will show you an integrated example on how to create a MIDlet form all these components.

  42. Your Profile: An integrated MIDlet Form • The following sample implement a simple MIDlet Form to enter the user personal profile for your MID - Profile.java • Profile contains the following items • A String Item - to show the title • Radio buttons (called Choice Group) - to select user gender • Text Box (called Text Field) - to enter user name • Date Field - to enter D.O.B. • Gauge Field - to enter the preferred phone volume Midlet API

  43. MIDlet Form example: Profile.java • Profile.java import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class Profile extends MIDlet implements CommandListener{ private Form mainscreen; private Command okCommand = new Command("OK", Command.OK, 1); private Command exitCommand = new Command("Exit", Command.EXIT, 1); private Display display; public Profile() { mainscreen= new Form("Your Profile"); mainscreen.addCommand(okCommand); mainscreen.addCommand(exitCommand); mainscreen.setCommandListener(this); //first create a stringItem mainscreen.append(new StringItem("Your Profile: ", "Please edit")); //create an imageItem Image img=null;

  44. MIDlet Form example: Profile.java try { img= Image.createImage("/profile.png"); } catch (Exception e) {} mainscreen.append(new ImageItem("", img,ImageItem.LAYOUT_CENTER, "Image can not display")); //select gender String[] editable_choices={"Mr.", "Ms."}; mainscreen.append(new ChoiceGroup("Gender: ",Choice.EXCLUSIVE, editable_choices,null)); //create a textfield mainscreen.append(new TextField("Name", "Raymond Lee", 20, TextField.ANY)); //create a datefield mainscreen.append(new DateField("D.O.B.", DateField.DATE)); //create a Gauge mainscreen.append(new Gauge("Phone Vol.",true,100,50)); //retrieve display object display=Display.getDisplay(this); }

  45. MIDlet Form example: Profile.java public void startApp() throws MIDletStateChangeException { display.setCurrent(mainscreen); } /** * Pause the MIDlet */ public void pauseApp() { } /** * Called by the framework before the application is unloaded */ public void destroyApp(boolean unconditional) { //clear everything mainscreen=null; okCommand = null; exitCommand = null; display=null; }

  46. MIDlet Form example: Profile.java • Profile.java (cont.) public void commandAction(Command c, Displayable d) { if(c==okCommand) { } else if(c==exitCommand) { destroyApp(true); notifyDestroyed(); } } }

  47. MIDlet Form example: Profile.java Your Profile: Entry Screen Choice Group: Your Gender Text & Date Fields Gauge : Volume • Gauge

  48. Canvas for drawing to the display The Canvas object defines several methods that are called by the implementation. These methods are primarily for the purpose of delivering events to the application, and so they are referred to as event delivery methods. The set of methods is: • showNotify() • hideNotify() • keyPressed() • keyRepeated() • keyReleased() • pointerPressed() • pointerDragged() • pointerReleased() • paint()

  49. Canvas : paint • protected abstract void paint(Graphics g) • ใช้สำหรับเขียนคำสั่งวาดภาพ • เหมือนกับใน Component ของ J2SE • ต่างกันที่ Class Graphics ของ MIDP

  50. Example: CircleCanvas import javax.microedition.lcdui.Canvas; import javax.microedition.lcdui.Graphics; publicclass CircleCanvas extends Canvas { intr=10; public CircleCanvas(int r) { super(); this.r = r; } protectedvoid paint(Graphics g) { int cx = g.getClipWidth()/2; int cy = g.getClipHeight()/2; g.setColor(0x00FF0000); // red g.fillArc(cx-r,cy-r,r*2,r*2,0,90); g.setColor(0x0000AA00); // green g.fillArc(cx-r,cy-r,r*2,r*2,90,90); g.setColor(0x000000CC); // blue g.drawArc(cx-r,cy-r,r*2,r*2,180,180); } }

More Related