Главная » Просмотр файлов » Programming Java 2 Micro Edition for Symbian OS 2004

Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 10

Файл №779882 Programming Java 2 Micro Edition for Symbian OS 2004 (Symbian Books) 10 страницаProgramming Java 2 Micro Edition for Symbian OS 2004 (779882) страница 102018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 10)

Typical examples of such applications would be games, wheregraphics require pixel-level placement on screen. As well as providingprecise control over object positioning, event listeners will monitor forprimitive events such as key presses and releases.

The developer also hasaccess to concrete keys and pointer actions. The Canvas and Graphicsobjects are the basis for the low-level API classes.Typically, these applications are less portable than those developedusing the high-level API. That does not mean, however, that theseapplications cannot be made to be portable. Some careful design toseparate the UI from the main game logic can yield economies of scaleINTRODUCTION TO MIDP31and a number of these techniques and theories will be investigated inChapter 6. The Canvas object provides methods for querying the sizeof the screen and also for identifying keys with the use of game-keymapping, which provides a generic method for accessing certain keys onthe keypad.

This mapping helps identify many of the actions requiredby games developers and maps the layout of certain keys on the pad tological positions a game player might assume when playing.2.1.2.2 The LCDUI ModelAt the basic abstraction level of the MIDP user interface is the Displayable object. This encapsulates device-specific graphics rendering,along with the user input, and only one Displayable object can bevisible at any one time. There are three types of Displayable objectacross the two APIs:• complex, predefined, immutable user interface components, such asList or TextBox• generic objects that may contain other objects or user interfacecomponents, such as a Form; input objects such as text fields can beappended to provide screens capable of capturing user input, entry ofa password, for example• user-defined screens, such as Canvas, a part of the low-level API.The first two are inherited from Screen, which is itself derived fromDisplayable and handles all the user interaction between the highlevel components and the application.

The Screen object also managesall the rendering, interaction, traversal and on-screen scrolling, regardlessof the device and the underlying implementation and it forms the basisfor portability of the applications using these APIs. In the case of the thirdtype of Displayable object, Canvas takes care of providing the basisof a UI with the low-level API classes.The Display class acts as the display manager for the MIDlet. EachMIDlet is initialized with a Display object.

There can only be onedisplay in action at any one time and user interaction can only be madewith the current display. The application sets the current display bycalling the Display.setCurrent(Displayable) method; it can, ofcourse, be any of the three Displayable object types.The display manager interacts with the AMS to render the currentdisplay on the screen. To understand how to structure the application inthe correct way, we need to look back at the MIDlet initialization processand lifecycle we examined in Section 2.1.1.

The MIDlet is initialized inthe paused state. Once the AMS has decided that the MIDlet is ready,it makes a call to the startApp() method. It should be remembered32GETTING STARTEDthat the startApp() method can be called many times during thelifecycle of a MIDlet, so the developer should be aware of what displayis made current and at what time. In MIDP 1.0, it was advised thatthe Displayable object was not truly visible until startApp() hadreturned. However, this requirement has been relaxed in MIDP 2.0.The Display.setCurrent(Displayable) method can, therefore,be carried out at MIDlet initialization and put in the MIDlet constructor.This also alleviates any problems the developer may experience withunwanted re-initialization of the application and its display after resumingfrom the paused state.2.1.2.3 The Event ModelThe javax.microedition.lcdui package implements an eventmodel that runs across both the high- and low-level APIs.

This handles such things as user interaction and calls to redraw the display. Theimplementation is notified of such an event and responds by making acorresponding call back to the MIDlet. There are four types of UI event:• events that represent abstract commands that are part of the highlevel API• low-level events that represent single key presses or releases, orpointer events in the case of pointer-based devices• calls to the paint() method of the Canvas class, generated forinstance by a call to repaint()• calls to a Runnable object’s run() method requested by a call tocallSerially() of class Display.All callbacks are serialized and never occur in parallel. More specifically, a new callback will never start while another is running. The nextone will only start once the previous one has finished, this will even betrue when there is a series of events to be processed.

In this case thecallbacks are processed as soon as possible after the last UI callbackhas returned. The implementation also guarantees that a call to run(),requested by a call to callSerially(), is made after any pendingrepaint() requests have been satisfied.There is, however, one exception to this rule: this occurs when theCanvas.serviceRepaints() method is called by the MIDlet. Thecall to this method causes the Canvas.paint() method to be invokedby the implementation and then waits for it to complete. This will occurwhenever the serviceRepaints() method is called, regardless ofwhere the method was called from, even if that source was an eventcallback itself.INTRODUCTION TO MIDP33Abstract commands are used to avoid having to implement concretecommand buttons; semantic representations are used instead.

The commands are attached to Displayable objects such high-level List orForm objects or low-level Canvas objects. The addCommand() methodattaches a Command to the Displayable object. The Command specifiesthe label, type and priority. The commandListener then implementsthe actual semantics of the command.

The native style of the device mayprioritize where certain commands appear on the UI. For example, ‘‘Exit’’is always placed above the right softkey on Nokia devices.There are also some device-provided operations that help contributetowards the operation of the high-level API. For example, screen objects,such as List and ChoiceGroup, will have built-in events that returnuser input to the application for processing.2.1.2.4 The High-Level APISince MIDP 1.0, the LCDUI classes have vastly improved, helping thedeveloper to create more intuitive, portable applications.

Figure 2.2shows the class diagram for both the high- and low-level APIs.Command ClassThe Command class is a construct that encapsulates the semantic meaningof an action. The behavior or response to the action is not itself specifiedby the class, but rather by a CommandListener. The command listeneris attached to a Displayable object. The display of this command willdepend upon the number and type of the other commands for that displayable object. The implementation is responsible for the representationCommandDisplayable0..*Display0..1ScreenItemFormAlertCanvasListGameCanvasTextBox(from javax.microedition.lcdui.game)0..*DateFieldImageItemStringItemFigure 2.2TextFieldGaugeCustomItemThe architecture of the LCDUI.ChoiceGroupSpacer34GETTING STARTEDof the command semantic information on screen; Command itself merelycontains the following four pieces of information about the command:• short labelThis string is mandatory.

The application can request the user tobe shown a label. Dependent upon the current layout and availablescreen space, the implementation will decide which is more appropriate. For command types other than SCREEN, a system-specific labelconsidered more appropriate for this command on this device mayoverride the labels provided.• long label – this longer label is optional; it will be used if there isenough space to display it• type – BACK, CANCEL, EXIT, HELP, ITEM, OK, SCREEN and STOPThis is used to indicate the command’s intent, so that the implementation can follow the style of the device.

For example, the ”back”operation on one device may always be placed over the right softkey.• priorityThis integer value describes the importance of the command relativeto other commands on the same screen. The implementation makesthe choice as to the actual order and placement of commands on thescreen. The implementation may, for example, first examine the command type to check for any particular style requirements and then usethe priority values to distinguish between the remaining commands.Screen ObjectsAlert, List, Form and TextBox are all derived from Screen, itselfderived from Displayable.

Screen objects are high-level UI components that can be displayed. They provide a complete user interface intheir own right, the specific look and feel of which is determined by theimplementation.Alert ObjectAn Alert object shows a message to the user, waits for a certain periodand then disappears, at which point the next Displayable object isshown. This object is intended as a way of informing the user of anyerrors or exceptional conditions.An Alert may be used by the developer to inform the user that anerror or other condition has been reached. To emphasize these states tothe user, the AlertType can be set to convey the context or importanceof the message.

For example, a warning sound may be played with thealert to draw the user’s attention to an error. A different sound can thenbe played when the alert is advisory. This can be achieved using theAlertType.playSound() method. Other types may also be set, suchINTRODUCTION TO MIDP35as ALARM, CONFIRMATION, ERROR and INFO. These manifest as titlesat the top of the alert screen.As well as providing text, an image can also be used to indicatethe nature of the alert. An exclamation mark may indicate an error, forexample. To ensure the user reads the message, the alert may be mademodal (the user must dismiss it before the next Displayable object isshown).

This is effectively achieved by setting an infinite timeout on thealert: setTimeout(Alert.FOREVER).An alert can also be used to show activity to the user. A gauge canbe added to the alert to indicate progress, for example, for loading anew level in a game or connecting to a remote server over HTTP. Anindicator is added by using the method setIndicator(Gauge). Thegauge object is subject to certain limitations: it cannot be interactive,owned by another Form or have Commands attached to it; nor can it bean ItemCommandListener.List ObjectA List object is a screen that contains a list of choices for the user.

Характеристики

Тип файла
PDF-файл
Размер
5,73 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6294
Авторов
на СтудИзбе
314
Средний доход
с одного платного файла
Обучение Подробнее