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

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

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

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

Ithas much in common with ChoiceGroup (it shares the same interface,Choice). However, a List cannot be added to a Form and is, in fact,a Displayable object in its own right. This means it is very good forimplementing a choice-based menu for the user. The Series 60 and UIQplatforms have a default ”Select” mechanism, which means a separateCommandListener does not have to be added to the list. A List canbe created by using one of the following two constructors:List menu = new List(String title, int listType)List menu = new List(String title, int listType, String[] stringElements,Image[] imageElements)The second constructor allows the developer to specify the itemswithin the list at creation rather than having to append, insert or setelements within the list.The list type can be EXCLUSIVE, where only one choice can be madeand one choice is selected at a time; MULTIPLE, which allows for morethan one selection; or IMPLICIT, in which case the currently focusedelement is selected when a command is initiated.Once the selection has been made, the index value or values of theselection can be captured by the application using one of two methods:• getSelectedIndex() returns the results of a list returning oneselection• getSelectedFlags(boolean[]) returns the flags for all the elements in a MULTIPLE list; the application can then loop through theflags to determine the user’s selections.36GETTING STARTEDForm ObjectThis Displayable object is designed to contain a small number ofclosely-related user interface elements.

Those elements are, in general,any subclass of the Item class and we shall be investigating these objectsin more detail below. The Form manages the traversal, scrolling andlayout of the form. It is defined by two constructors:Form (String title)Form (String title, Item[] items)Items enclosed within a Form may be edited using the append(),delete(), insert() and set() methods and they are referred to bytheir indexes, starting at zero and ending with size()−1. A distinctItem may only be placed upon one Form at a time. If an attempt ismade to put the same instance of Item on another Form, an IllegalStateException will be thrown.Items are organized via a layout policy that is based around rows.The rows typically relate to the width of the screen and are constantthroughout.

Forms grow vertically and a scroll bar will be introduced asrequired. If a form becomes too large, it may be better for the developerto create another screen. The layout algorithm used in MIDP 2.0 will bediscussed in greater detail in Chapter 3.Users can, of course, interact with a Form, and a CommandListenercan be attached to capture this input using the setCommandListener() method. An individual Item can be given an ItemCommandListener if a more contextual approach is required by the UI.TextBox ObjectA TextBox is a Screen object that allows the user to enter and edittext in a separate space away from the form.

This is a Displayableobject and can, therefore, be displayed on the screen in its own right.Its maximum size can be set at creation, but the number of charactersdisplayed at any one time is unrelated to this size and is determined bythe device itself.Item ClassThis is the superclass for all items that can be added to a Form. EveryItem has a label, which is a string. This label is displayed by theimplementation as near as possible to the Item, either on the samehorizontal row or above.When an Item is created, by default it is not owned by any containerand does not have a Command or ItemCommandListener. However,default commands can be attached to an Item, using the setDefaultCommand() method, which means the developer can make the userinterface more intuitive for the user.

A user can then use a standardINTRODUCTION TO MIDP37gesture, such as pressing a dedicated selection key or tapping on the itemwith a pointer. Symbian devices support both interfaces through Series60 and UIQ respectively. As a side issue, it should be noted that the useof default commands can disrupt the use of layout directives. Normalcommands can also be attached to items using the setDefaultCommand(Command) method.

Developers who use the low-level API willbe quite familiar with this method.A new set of properties that determine the minimum and preferredwidth and height of an Item has been added in MIDP 2.0. This can beused by the device implementation to determine how best to render theitem on the screen and will be discussed further in Chapter 3.The following types are derived from Item.ChoiceGroupA ChoiceGroup is a group of selectable objects. It may be used tocapture single or multiple choices placed upon a Form. It is a subclass ofItem and most of its methods are implemented via the Choice interface.It can be created using one of two constructors:ChoiceGroup (String title, int type);ChoiceGroup (String title, int type, String[] elements,Image[] image Elements);The first, a simpler constructor, allows the developer to create anempty choice group, specifying its title and type, and append elementsafterwards.

The type can be either EXCLUSIVE (to capture one optionfrom the group) or MULTIPLE (to capture many selections).A developer who already knows the contents of the choice group maychoose to use the second constructor. This has the advantage that allentries are created at the same time but, of course, the contents of thegroup may still be dynamic. Just as a List can be changed after creation,so the contents of the choice group can be changed.

Insert, append andreplace functionality is present. Each choice is indexed, incrementing by1 from the first item being 0.It is the responsibility of the device implementation to provide thegraphical representation of the option group. For example, one devicemay use ticks to represent selected options in a multiple choice group andradio buttons to denote an exclusive selection.

Another device, however,may choose to display these items another way. The point here is that thedeveloper does not have control over the appearance of these items onthe screen.CustomItemThis is one of the most interesting MIDP 2.0 additions to the high-levelAPI. It operates in a similar way to Canvas, in that the developer is able38GETTING STARTEDto specify what content appears where within the CustomItem. Thedeveloper has free rein to create an item that suits the purposes of theapplication.Some of the standard items may not give quite the required functionality, so it may be better to define home-made ones instead. The onlydrawback to this approach is that, as well as having to draw all the contents using the item’s paint() method, the programmer has to processand manage all events, such as user input, through keyPressed().Custom items may interact with either keypad or pointer-based devices.Both are optional within the specification and the underlying implementation will signal to the item which has been implemented.

In the case ofSymbian, these can be either UIQ or Series 60 devices.Deriving from Item, CustomItem also inherits such methods asgetMinContentWidth() and getPrefContentHeight() whichhelp the implementation to determine the best fit of items within thescreen layout. If the CustomItem is too large for the screen dimensions,it will resize itself to within those preferred, minimum dimensions. Thesechanges will be notified to the CustomItem via the sizeChanged()and paint() methods.As we have seen, the developer has total control over what appears on aCustomItem and the item is responsible for rendering itself to the display.Additionally, the developer can use the Display.getColor(int) andFont.getFont(int) methods to determine the underlying propertiesfor items already displayed in the form of which the CustomItem willbe a part.

This will ensure that a consistent appearance is maintained.DateFieldThis is an editable component that may be placed upon a Form to captureand display date and time (calendar) values. When the item is added tothe form it can be set with or without an initial value. If the value is not set,a call to the getDate() method will return null. The field can handleDATE values, TIME values or both, DATE_TIME values.

Where both arespecified, the user interface will manage one after the other when lookingfor input. Calendar calculations made from this field are based upon thedefault locale and time zone definitions stored on the device.ImageItemThe ImageItem is a reference to a mutable or immutable image thatcan be displayed on a Form. We shall look at the Image object in detailwhen we examine the low-level API classes. Suffice to say that the Imageis retrieved from the MIDlet suite’s JAR file in order to be displayed uponthe form. This is performed by calling the following method, in this casefrom the root directory:Image image = Image.createImage("/myImage.png");INTRODUCTION TO MIDP39This returns an Image object that can be used to create the ImageItem.An ImageItem is created by calling one of two constructors:ImageItem imageItemint layout,ImageItem imageItemint layout,= new ImageItem (String label, Image image,String altText);= new ImageItem (String label, Image image,String altText, in appearanceMode);A title for the item can be defined along with a combination of layoutconstants that determine how the image should be laid out.

The altTextparameter will be displayed by the implementation if it establishes thatthe image is too large for the current display. The second constructor addsanother parameter that determines the appearance of the ImageItem.The appearanceMode parameter values may be PLAIN, HYPERLINKor BUTTON. The preferred and minimum sizes may be affected if thesecond or third options are used.SpacerThis is a blank non-interactive item with a definable minimum size,which was added as part of the MIDP 2.0 specification.

It is used forallocating flexible amounts of space between items on a form and givesthe developer much more control over the appearance of a form. Theminimum width and height for each spacer can be defined to providespace between items within a row or between rows of items on the form.StringItemThis is an item that can contain a string.

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

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

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

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