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

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

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

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

On the Nokia6600, the default value can be changed by the user to oneshot or disallowed. For the Sony Ericsson P900/P908, the security policy in effect forMIDlets in MIDlet suites bound to the trusted protection domain allowsautomatic access to the Push Registry API.3.3.5.4 Symbian’s ImplementationAt the time of writing, the current version of Symbian OS, Version 7.0s,supports the following connection types in its implementation of theMIDP 2.0 push architecture:• Server socket• Datagram• SMS.In Symbian’s implementation, all connections that can be registered aspush connections are managed by the system AMS, even if they are notrequested to be push-enabled by an application.

In the case of serverconnections that spawn off a connected stream due to an incomingconnection, the stream connections are also maintained through thesystem AMS.Future releases of Symbian OS are likely to increase the types ofconnections supported by the push architecture to include Bluetooth,L2CAP and RFCOMM connections.3.3.6 Additions to the LCDUI3.3.6.1 A Quick TourThe MIDP 2.0 specification introduces a number of new features to theLCDUI toolkit which are designed to give developers more control overtheir application’s user interface.

In this section we briefly look at someof them.DisplayMIDP 2.0 introduces two useful new methods to the Display classwhich allow MIDlets to control the screen backlight and the vibration ofthe phone:124MIDP 2.0 AND THE JTWIpublic boolean flashBackLight(int duration)public boolean vibrate(int duration)The duration of the effect is specified by the duration parameter – avalue of zero causes the action to stop. The return value is false if therelevant feature is not supported by the phone.FormMIDP 2.0 introduces a new layout algorithm for arranging items ina Form. The layout algorithm arranges items in rows according to alayout direction defined by the implementation for the language convention in use.

For European and North American markets the defaultlayout direction will be left to right. The layout algorithm then arrangesitems from left to right and starts a new row when there is insufficient space in the row to accommodate the next Item. The layoutalgorithm uses the concept of current alignment. For an implementation with a left to right layout direction the initial current alignment isItem.LAYOUT_LEFT. Other possible values for the current alignmentare Item.LAYOUT_RIGHT and Item.LAYOUT_CENTER. The currentalignment changes when the layout algorithm encounters an Item witha (horizontal) layout value other than the current setting (the layout directive for an Item is set using the setLayout() method).

When thishappens, the layout algorithm adds that Item on a new row and uses thenew alignment value until an Item with a different horizontal directiveis encountered.Vertical layout directives provided are Item.LAYOUT_TOP, Item.LAYOUT_BOTTOM and Item.LAYOUT_VCENTER. These are used to indicate the required vertical alignment of an Item within the current row.MIDP 2.0 added the getPreferredWidth(), getPreferredHeight(), getMinimumWidth() and getMinimumHeight() methods to the Item class.

These are used by the form layout algorithmto position and size Items within rows. In addition a MIDlet caninfluence the size of an Item by using the Item.LAYOUT_EXPAND,Item.LAYOUT_VEXPAND and Item.LAYOUT_SHRINK and Item.LAYOUT_VSHRINK directives.When filling a row, the layout algorithm first adds each Item according to its preferred width (or minimum width, if the LAYOUT_SHRINKdirective is set).

Once the row has been filled, any remaining space isproportionately distributed amongst the items by expanding their widths.Any Item with the LAYOUT_SHRINK directive set is expanded to nomore than its preferred size and then any remaining space is taken upexpanding Items with the LAYOUT_EXPAND directive set.The height of a row is determined by the tallest Item in the row.The height of an Item is determined by its preferred height (unlessthe LAYOUT_VSHRINK directive has been set, in which case initially theMIDP 2.0125minimum height is used). Once the height of the row has been determined,any Item shorter than the row height that has its LAYOUT_VEXPANDdirective set is expanded to the height of the row.

Any Item with itsLAYOUT_VSHRINK directive set is expanded to its preferred size or theheight of the row, whichever is shorter. Finally, any Item with verticaldirectives (LAYOUT_TOP, LAYOUT_BOTTOM or LAYOUT_CENTER) set ispositioned accordingly in the row. Remaining items with no verticaldirective are positioned at the bottom of the row.It is possible to force a row break using setLayout(Item.LAYOUT_NEWLINE_BEFORE) and setLayout(Item.LAYOUT_NEWLINE_AFTER). In the first case, the item will be added on a new row. Inthe second case, a row break will occur immediately after the item thatcalled the method. Note that for backward compatibility with MIDP1.0, TextField, DateField, Gauge and ChoiceGroup items arealways positioned with a row to themselves unless the Item.LAYOUT_2directive has been set.ItemMIDP 2.0 introduces new features into the Item class including:• support for the new layout algorithm with new directives defined aspublic static final int (see above)• the addCommand() method; an item can have commands associatedwith it• the setItemCommandListener() method• the getMinimumHeight(), getMinimumWidth(), getPreferredHeight()and getPreferredWidth() methods.It also introduces new public static final int appearance modes:• BUTTON indicates the item is to appear as a button• HYPERLINK indicates the item is to appear as a hyperlink• PLAIN indicates the item is to have a normal appearance.CustomItemThis is a new class introduced in MIDP 2.0 that can be sub-classed tocreate new visual elements for use in Forms.StringItemMIDP 2.0 introduces a new constructor to the StringItem class thatcreates a StringItem with the indicated appearance mode: PLAIN,BUTTON, or HYPERLINK.public StringItem(String label,String text,int appearanceMode)126MIDP 2.0 AND THE JTWIItemCommandListenerA listener type introduced in MIDP 2.0 for receiving notification ofcommands that have been invoked on Item objects.SpacerA new class introduced in MIDP 2.0 representing a blank Item with asettable minimum size whose primary purpose is to position other items.ChoiceNew features introduced in MIDP 2.0 to the Choice interface include:• static int POPUP• static int TEXT_WRAP_DEFAULT• static int TEXT_WRAP_OFF• static int TEXT_WRAP_ON• deleteAll()• getFitPolicy()• getFont()• setFitPolicy(int fitPolicy)• setFont(int elementNum, Font font).3.3.6.2 Exploring the LCDUI: the KeyPad ExampleRather than exploring the new features of the LCDUI API by API, we willinstead discuss an example MIDlet that illustrates some of the features.For a more thorough exposition of the LCDUI APIs, the reader is referredto Sun’s MIDP 2.0 documentation.We will use as the example a simple numeric keypad.

Screenshots ofour KeyPad MIDlet running on the Series 60 and UIQ reference designsare shown in Figure 3.7.The KeyPad MIDlet consists of two classes: the KeyPad class extendsMIDlet and provides the main UI in the guise of a Form instance; andthe Button class extends CustomItem and models a simple button.The Button instances are appended to the Form to create our keypad.First, let’s consider the KeyPad class:import javax.microedition.midlet.MIDlet;import javax.microedition.lcdui.*;public class KeyPad extends MIDlet implements CommandListener {private Display display;private Form container;private Command exit;MIDP 2.0Figure 3.7The KeyPad MIDlet on Series 60 and UIQ.private Command clear;private TextField field;public KeyPad() {display = Display.getDisplay(this);container = new Form("");clear = new Command("CLEAR",Command.SCREEN,1);exit = new Command("EXIT",Command.EXIT,1);container.addCommand(exit);container.addCommand(clear);container.setCommandListener(this);ButtonButtonButtonButtonButtonButtonButtonButtonButtonButtonone = new Button(this, "1");two = new Button(this, "2");three = new Button(this, "3");four = new Button(this, "4");five = new Button(this, "5");six = new Button(this, "6");seven = new Button(this, "7");eight = new Button(this, "8");nine = new Button(this, "9");zero = new Button(this, "0");field = new TextField(null,null,32,TextField.UNEDITABLE);int bheight = one.getPrefContentHeight(-1);int bwidth = one.getPrefContentWidth(-1);127128MIDP 2.0 AND THE JTWIcontainer.append(new Spacer(container.getWidth(),bheight/2));container.append(new Spacer (bwidth/2, bheight));container.append(one);container.append(new Spacer (bwidth/2, bheight));container.append(two);container.append(new Spacer (bwidth/2, bheight));container.append(three);container.append(new Spacer(container.getWidth(),bheight/4));container.append(new Spacer (bwidth/2, bheight));container.append(four);container.append(new Spacer (bwidth/2, bheight));container.append(five);container.append(new Spacer (bwidth/2, bheight));container.append(six);container.append(new Spacer(container.getWidth(),bheight/4));container.append(new Spacercontainer.append(seven);container.append(new Spacercontainer.append(eight);container.append(new Spacercontainer.append(nine);container.append(new Spacercontainer.append(zero);(bwidth/2, bheight));(bwidth/2, bheight));(bwidth/2, bheight));(bwidth/2, bheight));container.append(new Spacer(container.getWidth(),bheight/2));container.append(field);}public void setString(String s) {String current = field.getString();field.setString(current.concat(s));}public void commandAction(Command c, Displayable d) {if(c == exit) {notifyDestroyed();}else if(c == clear) {field.setString("");}}public void startApp() {display.setCurrent(container);}public void pauseApp() {MIDP 2.0129}public void destroyApp(boolean unconditional) {}}The main work is done in the constructor.

We create the Form, plusa couple of Command instances. We add the commands to the form andset the CommandListener. Then we create various instances of ourButton and a TextField to display the output of the button presses.We append the Button instances to the Form, separated by instancesof the Spacer class, plus the TextField instance. We implement asetString() callback method that is invoked by a Button instance,taking the button’s label as its parameter. Finally, we implement thecommandAction() method mandated by the CommandListenerinterface, which our KeyPad class implements.Now let’s look at the Button class:import javax.microedition.lcdui.*;public class Button extends CustomItem{private static final int HEIGHT = 20;private static final int WIDTH = 20;private static final int DELTA = 2;private String num;private KeyPad pad;public Button(KeyPad pad, String num){super("");this.pad = pad;this.num = num;}protected void paint(Graphics g, int w, int h){g.setColor(0, 0, 0);g.fillRect(0, 0, WIDTH+DELTA, HEIGHT+DELTA);g.setColor(128, 128, 128);g.fillRect(0, 0, WIDTH-DELTA, HEIGHT-DELTA);int xOffset = WIDTH/3;int yOffset = 2*HEIGHT/3;g.setColor(255, 255, 255);g.drawString(num, xOffset, yOffset,Graphics.BASELINE | Graphics.LEFT);}protected int getPrefContentHeight(int width) {return getMinContentWidth();}protected int getPrefContentWidth(int height) {return getMinContentHeight();}protected int getMinContentHeight() {130MIDP 2.0 AND THE JTWIreturn HEIGHT;}protected int getMinContentWidth() {return WIDTH;}protected void pointerPressed(int x, int y) {pad.setString(num);}public void keyPressed(int keyCode){int gameAction = getGameAction(keyCode);if (gameAction == Canvas.FIRE){pad.setString(num);}}}The constructor takes as arguments the KeyPad instance, to facilitate acallback, and a String acting as the button label.

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

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

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

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