Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 12
Текст из файла (страница 12)
It is a display-only item andthe user cannot edit the contents. Both the label and content of theStringItem can, however, be changed by the application. As withImageItem, its appearance can be specified at creation as one ofPLAIN, HYPERLINK or BUTTON. The developer is able to set the textusing the setText() method and its appearance using setFont().TextFieldA TextField is an editable text component that may be placed upon aForm.
It can be given an initial piece of text to display. It has a maximumsize, set by setSize(int size), and an input mask, which can be setwhen the item is constructed.An input mask is used to ensure that end-users enter the correctdata. This can reduce user frustration which, considering the inputmethods available to mobile devices, is very useful. The followingmasks can be used: ANY, EMAILADDR, NUMERIC, PHONENUMBER,URL, DECIMAL. These constraints can be set using the setConstraints() method and retrieved using getConstraints(). Theconstraint settings should be used in conjunction with the following set of40GETTING STARTEDmodifier flags using the bit-wise AND (&) operator: PASSWORD, SENSITIVE, UNEDITABLE, NON_PREDICTIVE, INITIAL_CAPS_WORD,INITIAL_CAPS_SENTENCE.TickerThis implements a ticker-tape object – a piece of text that runs continuously across the display.
The direction and speed of the text is determinedby the device. The ticker scrolls continuously and there is no interface tostop and start it. The implementation may pause it when there has beena period of inactivity on the device, in which case the ticker will resumewhen the user recommences interaction with the device.The Ticker is created using the constructor Ticker(Stringtext); the currently displayed text is returned by getString(); andthe text is set or reset using setString(String text).InterfacesFour interfaces are provided by the user interface package, javax.microedition.lcdui. They are available to both the high- and lowlevel APIs.• Choice defines an API for user interface components such as Listand ChoiceGroupThe contents of these components are represented by strings andimages which provide a defined number of choices for the user.
Theuser’s input can be one or more choices and they are returned to theapplication upon selection.• CommandListener is used by applications that need to receivehigh-level events from the implementation; the listener is attached toa Displayable object within the application using the addCommand() method• ItemCommandListener is a listener type for receiving notificationof commands that have been invoked on Item objectsThis provides the mechanism for associating commands with specificForm items, thus contextualizing user input and actions according tothe current active item on the Form, making it more intuitive.• ItemStateListener is used by applications that need to receiveevents that indicate changes in the internal state of the interactive itemswithin a Form; for example, a notification is sent to the applicationwhen the set of selected values within a ChoiceGroup changes.2.1.2.5 The Low-Level APIGraphics and the CanvasThe low-level API provides the developer with a much more flexibleapproach to user interface development.
Whereas the high-level classesINTRODUCTION TO MIDP41leave the implementation to manage the display, the low-level API provides fine-grained control of the display to the developer. The programmerhas pixel-level control over the positioning of objects on the screen andcan also define objects through the extensive graphics facilities available.Canvas, the main base class for low-level application programming,allows the developer total control over the display.
The developer mayspecify down to pixel level the position of objects on the screen. Toimplement Canvas, the application should subclass it to create a newDisplayable screen object. As it is Displayable, it is interchangeablewith other screen objects such as List and Form. The developer maychoose to use the high-level user interface classes when creating the UIby toggling between the two types.Canvas is most commonly used by game developers when creatingsprite animation, and it also forms the basis of GameCanvas, which is partof the new MIDP 2.0 Game API and will be examined later in this chapterand in more detail in the next. Canvas can be used in two modes.
Normalmode allows for the display of other information such as softkey labels,title and other device information screen furniture. In full screen mode,set by calling the setFullScreenMode(boolean mode) method, theCanvas takes up as much of the display as the implementation will allow.In either mode, the dimensions of the Canvas can be accessed using thegetWidth() and getHeight() methods.Graphics are drawn to the screen by implementing code in the abstractpaint() method. This method must be present in the subclass and willbe called as part of the event model. The event model provides a seriesof methods that include user input methods such as keyPressed()and pointerPressed(), depending upon the device’s data inputimplementation. All the methods are called serially except serviceRepaints() which blocks all other events until paint() has returned.
Inother words, if serviceRepaints() is called, then it will be servicedbefore calls to the others are resumed.The paint(Graphics g) method provides a graphics object, whichis used to draw to the display. The Graphics object provides a simple2D geometric rendering capability. Rendering operations are based uponpixel replacement. Source pixels from the graphics context replace thedestination pixels in the display object. Transparency is also supportedand is implemented by leaving the pixel in an unchanged state.
The colorcontext can be set using the setColor (int red, int green,int blue) method.An Image is drawn using the drawImage(Image image, int x,int y, int anchor) method of the Graphic class, which specifiesthe location of an Image object on the display.
Other primitives may alsobe drawn: strings are drawn using drawstring(String string,int x, int y, int anchor) and rectangles using drawRectangle(int x, int y, int width, int height).42GETTING STARTEDSuch methods as keyPressed() and pointerPressed() represent the interface methods for the CommandListener. When a key ispressed, it returns a keyCode to the command listener. These keyCodes are mapped to keys on the keypad. The keyCode values areunique for each hardware key, unless keys are obvious synonyms for oneanother. These codes are equal to the Unicode encoding for the character representing the key.
Examples of these are KEY_NUM0, KEY_NUM1,KEY_STAR, KEY_POUND, to mention a few. The problem with these keycodes is that they are not necessarily portable across devices: other keysmay be present on the keypad and will perhaps form a distinct list fromthose described previously. It is therefore better, and more portable, touse game actions instead.Each keyCode can be mapped to a game action using the getGameAction(int keyCode) method. This translates the key code into constantssuch as LEFT, RIGHT, FIRE, GAME_A and GAME_B.
Codes can translatedback to keyCodes by using getKeyCode(int gameAction). Apartfrom making the application portable across devices, these game actionsare mapped in such a way as to suit gamers. For example, the LEFT, RIGHT,UP and DOWN game actions might be mapped to the 4, 6, 2 and 8 keys onthe keypad, making game-play instantly intuitive.Typically, a simple Canvas class might look like this:import javax.microedition.lcdui.*;public class SimpleCanvas extends Canvas {public void paint(Graphics g) {// set color context to be blackg.setColor(255, 255, 255);// draw a black filled rectangleg.fillRect(0, 0, getWidth(), getHeight());// set color context to be whiteg.setColor(0, 0, 0);// draw a string in the top left corner of the displayg.drawString("This is some white text", 0, 0, g.TOP | g.LEFT);}}ThreadingWhile we are looking at the low-level API, it is worth having a quicklook at threading.
Threading can be used to create animation within anapplication; there are many ways in which this can be done.Timers can be used, but the most common way to create a thread is toimplement a Runnable interface. Typically, it would be best to make theCanvas class Runnable and use this as the central core of any animatedapplication. Implementing this interface specifies that the abstract run()method must be implemented and this is where the main work of thethread will be carried out. Normally, a Thread object is instantiated andthe Runnable class itself is passed as the target. The following shows aframework that might be adopted:INTRODUCTION TO MIDP43import javax.microedition.lcdui.*;public class ThreadedCanvas extends Canvas implements Runnable {private Thread thread;private boolean isRunning;private final int SLEEP = 50;ThreadedCanvas() {// initialize the class here.}synchronized void start() {isRunning = true;thread = new Thread(this);thread.start();}synchronized void stop() {isRunning = false;}public void run() {// put the main game logic in herewhile (isRunning) {// perform thread tasks// repaint}try {Thread.sleep(SLEEP);}catch (Exception e) {}}public void paint(Graphics g) {// paint Graphics object to the screen}}The Game APIProbably one of the most useful additions to the MIDP 2.0 programmingenvironment is the creation of the Game API.