Горн а ков С. Г.
Программирование мобильных телефонов на Java 2 Micro Edition т-д Компакт-qucK к книге
•
Расширьте
т возможности вашего" тел ефона!
•ЁЙИВйШ^^л*»*^'-"" '
ДЛЯ
•
МФШИШШИ
Горнаков С. Г.
ПРОГРАММИРОВАНИЕ МОБИЛЬНЫХ ТЕЛЕФОНОВ НА JAVA 2 MICRO EDITION
Москва, 2005
-
УДК 004.438 ББК 32.973.26-018.2
Г26
Горнаков С. Г. Программирование мобильных телефонов на Java 2 Micro Edition. - М.: ДМК Пресс, 2004. - 336 с.: ил. ISBN 5-94074-279-3 Книга, которую вы держите в руках, представляет платформу Java 2 Micro Edition, являющуюся стандартом в программировании приложений для мобильных телефонов. В книге подробно и доступно объясняется архитектура платформы Java 2 Micro Edition, состоящей из конфигураций и профилей. Рассматриваются две имеющиеся на данный момент версии профилей MIDP 1.0 и MIDP 2.0, на базе которых происходит построение мобильных приложений. В контексте этой книги изучаются основы построения мобильных программ, использование графики, техника создания игр для телефонов, работа со звуком. Разбирается большое количество классов пользовательского интерфейса, необходимых для создания интуитивно понятного и красивого интерфейса программ. Рассматриваются бесплатные среды программирования мобильных приложений от компании Sun Microsystems. Это Sun ONE Studio 4 Mobile Edition и Wireless Toolkit 2.1, а так же отдельные инструментарии от известных производителей телефонов Nokia, Siemens, Sony Ericsson, Motorola, Samsung для эмуляции мобильных устройств на компьютере. Книга будет интересна как начинающим программистам, так и более опытным не знакомым с платформой Java 2 Micro Edition. Поскольку в книге содержатся основы языка программирования Java, то пользоваться этой книгой могут и неподготовленные читатели. Книга также содержит полный справочник по интерфейсам, классам, методам, константам и исключениям платформы Java 2 Micro Edition. УДК 004.438 ББК 32.973.26-018.2 Все права защищены. Любая часть этой книги не может быть воспроизведена в какой бы то ни было форме и какими бы то ни было средствами без письменного разрешения владельцев авторских прав. Материал, изложенный в данной книге, многократно проверен. Но поскольку вероятность технических ошибок все равно существует, издательство не может гарантировать абсолютную точность и правильность приводимых сведений. В связи с этим издательство не несет ответственности за возможные ошибки, связанные с использованием книги.
ISBN 5-94074-279-3
© Горнаков С. Г., 2005 © Оформление, ДМК Пресс, 2005
Содержание Предисловие
11
Что вы должны знать Какое программное обеспечение используется О чем эта книга ...:.... Содержание компакт-диска Исходные коды Благодарности Об авторе
Глава 1. Устройство мобильных телефонов., 1.1. Стандарт GSM 1.2. Архитектура телефонов 1.3. Прошивка и операционная система 1.4. Инфракрасный порт 1.5. Технология Bluetooth ,.. 1.6. Протокол WAP 1.7. Протокол GPRS 1.8. Карта SIM
..
Глава 2. Платформа Java 2 Micro Edition 2.1. Конфигурация CDC 2.2. Конфигурация CLDC 2.2.1. Свойства языка Java 2.2.2. Виртуальная машина ... 2.3. Профиль 2.4. Профиль MIDP 2.0 и конфигурация CLDC 1.0 2.4.1 Пакет Java.lang , 2.4.2. Пакет java.util 2.4.3. Пакетjava.io 2.4.4. Пакетjavax.microedition.io 2.4.5. Пакетjavax.microedition.lcdui 2.4.6. Пакет javax.microedition.lcdui.game 2.4.7. Пакет javax.microedition.media 2.4.8. Пакет javax.microedition.media.control 2.4.9. Пакетjavax.microedition.midlet 2.4.10. Пакет javax.microedition.pki 2.4.11. Пакет javax.microedition.rms
12 13 13 14 15 ...15 15
16 17 17 17 18 19 19 20 21
22 24 25 26 26 27 29 29 .31 '. 32 34 35 37 ....37 .-.., ..38 38 39 39
Содержание Глава 3. Средства разработки мобильных приложений... 41 3.1. Установка Java 2 SDK SE 41 3.2. Среда программирования SUN ONE Studio 4 Mobile Edition ... 42 3.2.1. Настройка SUN ONE Studio 4 Mobile Edition 44 3.2.2. Создание проекта в SUN ONE Studio 4 Mobile Edition .... 50 3.2.3. Создание приложений в SUN ONE Studio 4 Mobile Edition 53 3.2.4. Компиляция и запуск программ в SUN ONE Studio 4 Mobile Edition .55 3.3. Среда программирования J2ME Wireless Toolkit 2.1 57 3.3.1. Установка J2ME Wireless Toolkit 2.1 57 3.3.2. Создание проекта в J2ME Wireless Toolkit 2.1 60 3.3.3. Компиляция и запуск программы в J2ME Wireless Toolkit 2.1 63 3.4. Упаковка программ 64 3.4.1. Файл манифеста 64 3.4.2. Файл JAD 65 3.4.3. Файл JAR : ..66
Глава 4. Телефонные эмуляторы
68
4.1. Программное обеспечение телефонов Nokia 69 4.1.1. Инструментарий Nokia Developer's Suite 2.0 for J2ME ...72 4.1.2. Программа Nokia PC Suite 5.1 77 4.1.3. Дополнительные пакеты Nokia 78 4.2. Программное обеспечение телефонов Siemens 78 4.2.1. Пакет Siemens Mobility Toolkit 79 4.2.2. Программа Siemens Date Suite 81 4.2.2. Дополнительные пакеты Siemens 81 4.3. Программное обеспечение телефонов Sony Ericsson 83 4.4. Программное обеспечение телефонов Motorola 85 4.5. Программное обеспечение телефонов Samsung 86
Глава 5. Механизм работы приложений Java 2 ME 5.1. Мидлет 5.1.1. Модель работы мидлета 5.2. Пользовательский интерфейс 5.3. Переход с экрана на экран 5.4. Навигация
Глава 6. Классы пользовательского интерфейса 6.1. Класс Form..
89 *
89 ...95 97 99 >.... 104
111 ..111
Содержание . 6.Т.1. Методы класса Form 6.2. Класс Item 6.2.1. Класс ChoiceGroup 6.2.2. Класс DateField 6.2.3. КлассTextField 6.2.4. Класс Stringltem 6.2.5. Класс Spacer 6.2.6. Класс Imageltem.... 6.2.7. toiaccGauge 6.3. Класс Alert. 6.3.1. Методы класса Alert , 6.4. Класс List 6.4.1. Методы класса List 6.5. Класс Ticker 6.5.1. Методы класса Ticker 6.6.1<ласс Image 6.6.1. Методы класса Image 6.7. Класс Font
IllHBHI
-.. .,
112 114 116 122 125 128 .. 133 135 139 142 142 145 146 152 152 154 154 , 156
Глава?. Программирование графики 7.1. Класс Canvas ...*...•'.. 7.1.1. Методы класса Canvas 7.2. Класс Graphics 7.2.1. Методы класса Graphics 7.3. Рисование линий :... 7.4. Рисование прямоугольников 7.5. Рисование дуг 7.6. Вывод текста 7.7. Механизм создания игрового цикла 7.8. Перемещение квадрата 7.9. Циклическое передвижение объекта по Экрану 7.10. Столкновение 7.11. Перемещение объекта с помощью клавиш
162 162 163 164 164 167 170 174 177 178 180 184 187 190
Глава 8. Техника создания игр
195
8.1. Класс GameCanvas 8.2. Класс Layer 8.3. Класс TiledLayer 8.4. Класс LayerManager 8.5. Класс Sprite 8.6. Создание фонового изображения
196 197 198 199 200 201
Содержание 2.3.6. Класс DataOutputStream 2.3.7. Класс InputStream 2.3.8. Класс InputStreamReader 2.3.9. Класс OutputStream 2.3.10. КлассOutputStreamWriter 2.3.11. Класс PrintStream 2.3.12. Класс Reader 2.3.13. Класс Writer 2.3.14. Исключения 2.4. Пакет javax.micro-edition.io ; 2.4.1. Интерфейс CommConnection 2.4.2. Интерфейс Connection 2.4.3. Интерфейс ContentConnection 2.4.4. Интерфейс Datagram 2.4.5. Интерфейс DatagramConnection 2.4.6. Интерфейс HttpConnection , 2.4.7. Интерфейс HttpsConnection 2.4.8. Интерфейс InputConnection 2.4.9. Интерфейс OutputConnection 2.4.10. Интерфейс SecureConnection 2.4.11. Интерфейс Securitylnfo 2.4.12. Интерфейс ServerSocketConnection 2.4.13. Интерфейс SocketConnection 2.4.14. Интерфейс StreamConnection 2.4.15. Интерфейс StreamConnectionNotifier 2.4.16. Интерфейс UDPDatagramConnection 2.4.17. Класс Connector 2.4.18. Класс PushRegistry 2.4.19. Исключение 2.5. Пакетjavax,microedition.lcdui 2.5.1. Интерфейс Choice 2.5.2. Интерфейс CommandListener 2.5.3. Интерфейс ItemCommandListener 2.5.4. Интерфейс ItemStateListener 2.5.5. Класс Alert 2.5.6. Класс AlertType 2.5.7. Класс Canvas 2.5.8. Класс ChoiceGroup 2.5.9. Класс Command ...' 2.5.10. Класс Customltem .
;
: :
290 291 291 292 292 293 294 ..294 295 295 295 295 295 296 296 ....296 298 298 298 298 298 299 299 299 299 299 300 300 301 301 301 ;.... 302 302 302 302 303 303 305 306 ..307
Содержание 2.5.11. Класс DateField 2.5.12. Класс Display 2.5.13. Класс Displayable 2.5.14. Класс Font .'; 2.5.15. Класс Form..... 2.5.16. Класс Gauge 2.5.17. Класс Graphics 2.5.18. Класс Image 2.5.19. Класс Imageltem 2.5.20. Класс Item 2.5.21. Класс List 2.5.22. Класс Screen 2.5.23. Класс Spacer 2.5.24. Класс Stringltem 2.5.25. КлассTextBox 2.5.26. Класс TextField 2.5.27. Класс Ticker 2.6. Пакетjavax.microedition.lcdui.game 2.6.1. Класс GameCanvas 2.6.2. Класс Layer 2.6.3. Класс LayerManager 2.6.4. Класс Sprite 2.6.5. КлассTiledLayer 2.7. Пакетjavax.microedition.media \........ 2.7.1. Интерфейс Control 2.7.2. Интерфейс Controllable ...., 2.7.3. Интерфейс Player 2.7.4. Интерфейс PlayerListener ..... 2.7.5. Класс Manager 2.7.6. Исключения 2.8. Пакет javax.microedition.media.control 2.8.1. ИнтерфейсToneControl 2.8.2. Интерфейс VolumeControl 2.9. Пакет javax.microedition.midlet 2.9.1. Класс MIDIet 2.9.2. Исключение 2.10. Пакет javax.microedition.pki... 2.10.1. Интерфейс Certificate.. 2.10.2. Исключение 2.11. Пакет javax.microedition.rms
..308 308 310 310 311 : ....:. 312 313 315 315 , 316 317 318 318 318 :. 319 320 321 321 321 322 322 ..323 324 324 324 324 325 325 326 326 326 .; 326 .' 327 327 ..327 328 328 328 328 328
Содержание 2.11.1. Интерфейс RecordComparator 2.11.2. Интерфейс RecordEnumeration 2.11.3. Интерфейс RecordFilter 2.11.4. Интерфейс Record Listener 2.11.5. Класс RecordStore
..,
328 329 329 329 330
Приложение 3. Структура компакт-диска
331
Список используемой литературы
333
Алфавитный указатель
334
шт Предисловие Рынок мобильных телефонов - это, пожалуй, самый быстроразвивающийся сегмент рынка. Несколько лет назад мобильный телефон был чем-то дорогим и недосягаемым. Оплата за связь была астрономической. Но времена меняются, связь подешевела, мобильные телефоны продаются на каждом углу и наличие телефона у человека можно уже сравнить с наличием обычных наручных часов. Обилие разнообразных моделей телефонов создает на этом рынке большую конкуренцию. Множество производителей стараются включить в телефоны как можно больше различных функций. Присутствием в телефоне адресной книги, органайзера, будильника и даже счетчика калорий уже никого не удивишь, и в какой-то момент времени возник вопрос, а чем же еще можно оборудовать телефон? Самым идеальным решением этого вопроса могла стать возможность загрузки в телефон программ сторонних производителей. Не секрет, что основная масса телефонов работает на основе прошивки, поэтому загрузка программ в телефон не возможна. Чтобы такая возможность появилась, производителям надо было бы решить ряд сложных вопросов. Во-первых — это язык программирования, на котором будут писаться программы для телефонов и, соответственно, поддержка этого языка самим телефоном. Второе — это аппаратная архитектура мобильных телефонов, которая сильно ограничена в своих системных ресурсах, а это процессор, память, графический интерфейс. Улучшение архитектуры неизменно ведет к увеличению стоимости телефона, поэтому идеальной в этом случае стала платформа Java 2 Micro Edition, созданная компанией Sun Microsystems. Платформа Java 2 ME состоит из виртуальной Java машины, языка программирования Java и огромного количества библиотек, облегчающих работу программиста. Язык программирования Java работает на основе интерпретации, поэтому для работы программ написанных на этом языке необходима виртуальная Java машина, встроенная в устройство, на котором планируется запускать Java программы. Наличие виртуальной Java машины в мобильном телефоне означает, что производитель поддерживает технологию Java. В данный момент практически все производители имеют поддержку Java технологии, что позволяет писать любые программы на этом языке и загружать их в телефон. Но и в этой сфере не обошлось без накладок. Появление большого количества производителей мобильных устройств в какой-то мере сопутствовало хаосу в стандартах, используемых при программировании телефонов. Каждая компания видела, да и, пожалуй, видит, свои пути развития в стандартизации своего программного обеспечения. Поэтому на рынке сейчас имеется масса инструментальных средств чуть ли не для каждой из моделей мобильных телефонов. В этом направлении, как мне кажется, сильно преуспела финская компания Nokia, явля-
Предисловие ющаяся законодателем мод, а может и лидером в производстве телефонов. Платформа Java 2 ME призвана обеспечить определенный стандарт в этой области. Каждый из телефонов, имеющийх поддержку Java, в теории может иметь совместимость с любым программным обеспечением, созданным на Java 2 ME. Вы спросите, почему в теории? Дело в том, что каждый из производителей телефонов имеет свои устоявшиеся характеристики по аппаратной части мобильного устройства. В большей степени это относится к дисплею телефона, модели графического интерфейса и отсутствию либо наличию различных комбинаций клавиш телефона. То есть любой программный код, написанный на Java 2 ME, обязан работать на любом телефоне с поддержкой Java. Но в виду всевозможных различий между марками, а иногда даже моделями телефонов от одного производителя, результаты могут быть несколько иными, рассмотрим пример с дисплеем. Телефоны Siemens с цветными дисплеями в своей массе имеют разрешение 101x80, тогда как у телефонов Nokia в большинстве доступно разрешение 128x128 пикселей и при этом каждая из марок телефонов имеет свои различия в графическом отображении некоторых элементов пользовательского интерфейса. Поэтому при программировании приложений, этот фактор придется иметь в виду. Как программист вы должны отвечать за совместимость написанной программы с различными моделями телефонов, что, безусловно, увеличит ваши трудности в создании хорошего приложения. Поговорив о капле дегтя в большой цистерне меда, перейдем к меду. Несомненно, Java 2 ME — это стандарт, обеспечивающий совместимость программного обеспечения с любой маркой телефона. Стремительное развитие технологий мобильных устройств обязано подразумевать определенный эталон в данном направлении. Немалое количество сторонних разработчиков при строгой стандартизации заинтересовано в развитии рынка программного обеспечения телефонов. В наше время телефон имеет почти каждый человек, в отличие, скажем от портативных компьютеров на основе операционных систем Palm и Pocket PC. Поэтому рынок мобильных устройств по своим масштабам считается наиболее перспективным, а платформа Java 2 ME, является стандартом в создании программ для телефонов. Язык программирования Java 2 ME сам по себе не сложен, а обилие готовых библиотек позволяет писать Java приложения за короткий промежуток времени. И что самое главное, наборы инструментальных средств программирования поставляемые компанией Sun Microsystems и производителями телефонов абсолютно бесплатны! Множество энтузиастов со всего мира в кратчайшие сроки создают как платные, так и бесплатные программы и игры на Java 2 ME. Задача этой книги - дать исчерпывающую информацию по программированию мобильных телефонов, поддерживающих платформу Java 2 ME.
Что вы должны знать Для того чтобы научиться программировать мобильные телефоны на Java 2 ME, вам необходимо знать только русский язык. Если вы новичок в программировании
О чем эта книга
1 1 I M H I
и не знакомы ни с одним языком программирования, то в приложении 1 содержится полная информация непосредственно по языку программирования Java. Изучив приложение 1, вы сможете научиться программированию телефонов на Java 2 ME и при ступить, к прочтению этой книги. Те читатели, которые уже знакомы с основами Java, могут сразу приступаить к прочтению книги с первой главы. Все главы книги написаны в доступной форме и рассчитаны на широкий круг читателей. Множество примеров с подробными комментариями призваны улучшить понимание общей концепции платформы Java 2 ME.
Какое программное обеспечение используется Естественно, что вся работа по созданию программ для мобильных телефонов происходит на компьютере и наличие мобильного телефона совсем не требуется. В качестве операционной системы используется Windows XP корпорации Microsoft. Большинство программного обеспечения находящегося на компактдиске ориентировано именно на эту операционную систему. Компакт-диск идущий в комплекте с этой книгой имеет просто потрясающий набор инструментальных средств для создания приложений на Java 2 ME. На компакт-диске вы найдете две бесплатные интегрированные среды программирования от компании Sun Microsystems, а также множество бесплатных инструментальных средств от таких известных компаний производителей телефонов как Siemens, Nokia, Sony Ericsson, Motorola и Samsung. Так же на компакт-диске находятся все исходные коды и программы из книги. Более подробное описание компакт-диска можно найти в приложении 3.
О чем эта книга Книга предназначена для самостоятельного изучения как языка программирования Java, так и для программирования приложений для мобильных телефонов. Подробно рассматриваются все имеющиеся пакеты библиотек Java 2 ME, разбираются классы, методы и интерфейсы, раскрывается механизм работы программ на Java 2 ME. Прочтение всей книги лучше осуществлять в хронологическом порядке, главу за главой. В приложении 2 содержится справочник, дающий исчерпывающую информацию по всем интерфейсам, классам, методам и константам платформы Java 2 Micro Edition. В первой главе рассматривается общая архитектура мобильных телефонов, разбирается аппаратная и программная часть, а так же принцип работы телефонов. Во второй главе изучаются основы платформы Java 2МЕ. Рассматриваются профили MIDP 1.0 и MIDP .2.0, являющиеся спецификацией, предъявляемой к аппаратной части телефона. Разбираются все имеющиеся в Java 2 ME классы, и прослеживается общая линия наследования классов и интерфейсов. В третьей главе объясняется установка, настройка и работа интегрированных сред, программирования. Будет изучено два .инструментария: Sun ONE Studio 4 Mobile Edition и J2ME Wireless Toolkit 2.1. Особое внимание уделяется компоновке и компиляции исходного кода.
Предисловие Четвертая глава повествует об имеющихся наборах инструментальных средств программирования (SDK), предоставляемых производителями телефонов. Анализируются инструментарии компаний Nokia, Siemens, Sony Ericsson, Motorola и Samsung. Все программные средства чаще всего поставляются в виде телефонных эмуляторов. Интегрируя эти наборы SDK в среды программирования, рассмотренные в главе 3, таким образом вы сможете тестировать созданные программы на-телефонах различных моделей. В пятой главе раскрывается механизм работы Java приложений, обсуждается принцип поэкранного отображения информации на дисплее телефона, и рассматриваются правила перехода и навигации в Java программах. Шестая глава полностью посвящена имеющимся в Java 2 ME классам пользовательского интерфейса. Использование этих классов в приложении помогает создать красочный и логически понятный интерфейс программы, В седьмой главе раскрываются секреты программирования графики. На практике объясняется механизм рисования графики и создание создания игрового цикла для профиля MIDP 1.0. Затрагиваются некоторые вопросы, связанные с передвижением и столкновением объектов в играх для мобильных телефонов. Восьмая глава освещает темы, связанные с техникой программирования игр для профиля MIDP 2.O. Будут проанализированы все имеющиеся игровые классы, вопросы связанные с анимацией, столкновением и перемещением объектов по экрану телефона. Девятая глава содержит подробное описание мультимедийной библиотеки, при помощи которой возможно осуществляется воспроизведение звуков на телефонах. В приложении 1 не искушенный в программировании читатель сможет изучить самостоятельно основы языка программирования Java. Используемый при освещении данной темы подход при освещении данной темы предоставляет читателю возможность в кратчайшие сроки получить всю необходимую информацию для последующего прочтения и понимания этой книги. Приложение 2 выполнено в виде справочника по всем основным интерфейсам, классам, методам и константам платформы Java 2 ME. Вся справочная информация разбита на соответствующие разделы и выстроена по алфавиту, что поможет читателю быстро найти подробную информацию о том или ином компоненте платформы Java 2 ME. Приложение 3 содержит описание структуры компакт-диска идущего в комплекте с книгой и содержащего программное обеспечение.
Содержание компакт-диска Компакт-диск содержит исходные коды и программы из книги. Кроме этого представлены две бесплатные среды программирования приложений для мобильных телефонов: Sun ONE Studio 4 Mobile Edition и J2ME Wireless Toolkit 2.1 компании Sun Microsystems, А так же большое количество инструментальных средств от компаний Nokia, Siemens, Sony Ericsson, Motorola, Samsung.
Об авторе
Исходные коды В книги для изучения предлагается большое количество исходного кода программ, на основе которых раскрываются различные секреты программирования приложений на Java 2 ME. Все исходные коды находятся на компакт-диске в папке \Code. Для того чтобы каждый раз вам не напоминать о местонахождении исходного, кода программы на диске, а также для быстрого нахождения кода программы в папке \Code, все примеры из книги имеют информационные названия, например: \Code\Listing6_3. Что говорит о том, что листинг под номером 6.3, находится в папке \Code. Более удобногоый варианта придумать сложно, поэтому в течение всей книги использоваласьуется именно такая модель работы с исходными кодами.
Благодарности Прежде всего, хочется поблагодарить свою жену Светлану, за помощь в создании рисунков к этой книге. Спасибо, без тебя было бы сложно все это нарисовать! За сборку компакт-диска необходимо поблагодарить Дмитрия Алексеевича Мовчана. Только благодаря Дмитрию Алексеевичу читатель имеет такую потрясающую коллекцию программного обеспечения различных производителей.
Об авторе Автор книги занимается профессиональным программированием на протяжении десятка лет. Им было создано большое количество программ и игр для компьютерных систем и мобильных телефонов в частности. Он также является автором книги «DirectX 9. Уроки программирования на C++». Написать автору можно по адресу электронной почты:
[email protected].
Глава 1. Устройство мобильных телефонов Прежде чем приступить к изучению особенностей программирования мобильных телефонов на Java 2 ME, необходимо познакомиться с общей схемой устройства телефона. Сейчас на рынке мобильных телефонов присутствует множество как мелких, так и крупных производителей мобильных телефонов, предлагающих широкий ассортимент продукции. По цене и по своим функциональным признакам имеющиеся устройства , можно условно разделить на три категории. Первая представляет собой мобильные телефоны с набором простейших функций, такие телефоны часто называют «звонилка». Функциональность подобных телефонов сводится только к их прямому назначению. С такого устройства можно произвести или принять вызов и воспользоваться услугами SMS , (Short Message Service — служба коротких сообщений). Сам телефон, как правило, имеет монохромный дисплей небольшого размера, а из пользовательских программ доступны только простейшие, такие как калькулятор, таймер, диктофон, телефонная книга и так далее. Вторая категория мобильных телефонов имеет более широкий круг возможностей. Дисплей таких телефонов обычно цветной, разрешение варьируется от 80 до 130 пикселей с глубиной цвета около пяти тысяч цветов. Телефоны этой категории обычно содержат те же возможности, что и у аппаратов первой категории и ряд дополнительных функций. Одна из них - это возможность загрузки приложений написанных на языке Java. Из всех дополнительных функций стоит выделить возможность работы с WAP (Wireless Application Protocol - протокол беспроводной передачи данных) и GPRS (General Packet Radio Service - радио сервис пакетной передачи данных). Принципы работы этих протоколов описывается в разделах 1.6 и 1.7 этой главы. Третья категория телефонов представляет собой так называемую бизнес-категорию. Подобные устройства имеют впечатляющие наборы функций, сравнимые с карманными портативными устройствами (КПК), а цена таких мобильных телефонов может быть достаточно высокой. Все три условные категории телефонов схожи одним - функцией связи, а различие в дополнительных возможностях вызвано условиями конкуренции между производителями и необходимостью продвижения новых технологий. Технический прогресс не стоит на месте, создаются все меньшие по размерам процессоры с более мощными характеристиками. Как мне кажется, рынок КПК со временем либо «умрет», либо само устройство КПК плавно ассимилируется в мобильные телефоны, что собственно уже и происходит. Как правило, все телефоны для связи используют стандарт GSM.
Прошивка и операционная система
1.1. Стандарт GSM Цифровой стандарт GSM (Global System Mobile Communication - система мобильной глобальной связи), на основе которого происходит связь между телефонами, - самый распространенный стандарт во всем мире, обеспечивающий диапазон работы мобильных телефонов на частотах 900/1800/1900 МГц. Стандарт GSM обладает качественными и безопасными характеристиками связи, что и повлияло на его популярность во всем мире. В нашей стране это основной стандарт, использующийся всеми крупными операторами связи.
1.2. Архитектура телефонов Не думаю, что стоит здесь приводить схемы печатных плат телефонов и разбирать тип установленных микросхем, все это больше подходит сериям книг «Радиолюбитель», но несколько слов об аппаратной части сказать все же необходимо. Телефон имеет процессор, память, приемо-передатчик, систему контроллеров для дисплея, клавиатуры, аккумулятора и карту SIM (Subscriber identification module — идентификационный модуль абонента). Процессор вкупе с памятью является сердцем телефона. Он имеет более скромные характеристики, чем процессор компьютера. Приемо-передатчик служит для приема и передачи сиг-' нала и включает в себя различные фильтры, кодеры, декодеры речи и сигналов. Система контроллеров для клавиатуры (клавиш телефона) и дисплея позволяет вводить информацию в телефон посредством клавиш и выводить ее на дисплей. Контроллер аккумулятора производит управление процессом зарядки аккумуляторных батарей телефона. Все аппаратное обеспечение телефона (железо) безусловно, само по себе функционировать не может, и работа осуществляется на основе прошивки или операционной системы.
1.3. Прошивка и операционная система Все имеющиеся мобильные телефоны можно разделить еще на два типа - это телефоны, работающие под управлением прошивки и телефоны, использующие операционную систему. Телефоны с операционной системой также носят название смартфоны. На рынке сейчас имеются две операционные системы, адаптированные под нужды телефонов, это Windows Mobile и Symbian. Операционная система Windows Mobile, за которой стоит, как не трудно догадаться, софтверный гигант Microsoft предъявляет достаточно высокие требования к аппаратной части телефона. Соответственно, высокая цена на такие устройства никак не способствует популяризации этой операционной системы. Но стоит признать тот факт, что операционная система Windows Mobile - очень мощная и хорошо продуманная система, которая в будущем возможно сможет занять одно из ведущих мест в этом сегменте рынка. Операционная система Symbian является открытой системой и предъявляет значительно меньше требований к аппаратному устройству телефона. В акцио-
Устройство мобильных телефонов нерное общество Symbian Ltd. (разработчик операционной системы Symbian) входят все мировые лидеры производителей телефонов. Эта операционная система на данный момент занимает доминирующее положение в мобильной промышленности. Обе операционные системы имеют различные наборы функциональных возможностей, но работа обеих похожа на работу компьютерных систем, конечно с учетом характеристик телефона, а это процессор, память, клавиатура, дисплей и так далее. Все эти факторы значительно уменьшают функциональность телефона, но прогресс не стоит на месте: в 1999 году процессор с частотой в 200 ГГц казался вершиной компьютерной техники, а сейчас об этом смешно вспомнить. Прошивка телефона - это программа, управляющая работой телефона, но вшитая в сам телефон. Каждый из производителей создает свои прошивки для конкретных моделей, предопределяя тем самым функциональность телефона. Операционная система разрешает осуществлять загрузку созданных программ в телефон, а в прошивке такая возможность не предусмотрена. Точнее сказать, не была предусмотрена до появления платформы Java 2 ME. Для работы приложений написанных на Java, необходима виртуальная Java машина или среда исполнения приложений. Виртуальная Java машина, адаптированная специально для телефонов, настолько компактна по размеру, и, что самое главное, безопасна, что практически все производители телефонов стараются создать поддержку Java программ, то есть встроить среду исполнения Java программ в телефон. Загрузка сторонних приложений дала очень мощный импульс мобильной игровой индустрии, что, как мне кажется, вывело телефон на новый более качественный уровень. Единственное что необходимо понимать в этом аспекте, это то, что среда исполнения Java-приложений в телефоне реализована таким образом, что не позволяет написать «вредные» программы портящие аппаратную часть телефона. Модель работы Java-программ реализована как бы в виде закупоренной бочки, в которой и происходит работа всех Java приложений. Из этой бочки программы выбраться не могут, а соответственно не могут и нанести ущерб телефону. Загрузка Java программ в телефой происходит при помощи программного обеспечения и кабеля, соединяющего телефон с компьютером. Также можно загрузить в телефон программы при помощи инфракрасного порта, технологии Bluetooth, либо непосредственно из Интернета с помощью протоколов WAP и GPRS. Все программы, загружаемые в телефон, распространяются в виде двух файлов, JAD *- это дескриптор приложения и JAR - архив программы. Более подробно процесс загрузки программ рассматривается в главе 3.
1.4. Инфракрасный порт Инфракрасный порт имеют не все телефоны. В основном это модели, относящиеся ко второй и третьей условной ценовой категории, о которых мы говорили в начале этой главы. С помощью инфракрасного порта можно произвести соединение с компьютером, другим телефоном или Любым иным устройством имеющим инфракрасный порт. Принцип работы инфракрасного порта очень прост:
Протокол WAP имеются светодиод и фотодиод, соответственно для передачи и приема сигнала. Поместив два устройства на расстоянии не более полутора метров в зоне прямой видимости можно осуществить связь между этими устройствами. Что касается связи телефона с компьютером посредством инфракрасного порта, то это происходит при помощи программного обеспечения поставляемого производителями телефонов. В частности на компакт диске можно найти программы для телефонов Sony Ericsson, Nokia и Siemens, подробный анализ этих программ вы найдете в главе 3.
1.5. Технология Bluetooth Название этой сравнительно новой технологии (Bluetooth - голубой зуб) позаимствовано из истории - так некогда звали датского короля Гарольда второго, стремящегося объединить все датские земли в одно королевство Дания. С помощью технологии Bluetooth можно осуществлять соединение сразу с множеством устройств и организовывать небольшие локальные сети. Связь с использованием Bluetooth происходит на частоте 2,4 ГГц с расстояния порядка 10 метров и что самое главное, не требует прямого соединения, то есть устройства могут находиться вне зоны видимости друг друга. Приемопередатчик сигнала выполняется в виде микросхемы и может связать в сеть около десятка разнообразных устройств. Сейчас технология Bluetooth очень активно используется производителями мобильных телефонов для создания беспроводных гарнитур, например наушника и микрофона.
1.6. Протокол WAP Протокол WAP (Wireless Application Protocol) - это протокол беспроводного соединения с сетью Интернет. Имея поддержку WAP в мобильном телефоне, появляется возможность выхода в Интернет для просмотра специально адаптированных web-страниц на телефоне. Также с помощью WAP можно скачать или купить игру или приложение, написанное на языке Java. Стоимость таких программ обычно не превышает 1-2 доллара. Однако пользоваться WAP можно только в том случае, если ваш оператор сотовой связи предоставляет WAP услуги. Телефон, имеющий поддержку WAP, снабжен и WAP-браузером, что и делает возможным просмотр WAP страниц в Интернете. Если обобщить все выше сказанное, то работу телефона с протоколом WAP, можно сравнить с обыкновенным компьютером, связывающимся с сетью Интернет, Все Интернет-страницы, используемые компьютерными системами написаны на языке HTML или XML, а страницы для WAP-соединения созданы с помощью своего языка WML (Wireless Markup Language - беспроводной язык разметки). Для того чтобы через WAP выйти в Интернет с мобильного телефона, необходимо обязательно произвести соответствующие настройки в телефоне. Сделать это можно вручную, а можно воспользоваться услугами своего оператора, предоставляющего мобильную связь. Для этого необходимо позвонить по соответствующе-
Устройство мобильных телефонов му номеру или отправить SMS, в зависимости от оператора связи указанного в инструкции, прилагающейся к SIM-карте. Если есть желание настроить WAP самостоятельно, то можно воспользоваться значениями, приведенными в таблице 1.1. Таблица 1.1. Операторы URL Защита связи Канал Входная точка Адрес IP Логин Пароль
Би Лайн http://wap.beeline.ru отключить GPRS http://wap.beeline.ru 192.168.017.001 beeline beeline
Мегафон http://wap.megawap.ru отключить GPRS http://wap.megawap.ru 010.010.001.002 wap wap ,
МТС
http://wap.mts'.ru отключить GPRS http://wap.mts.ru 212.44.140.13 mts mts
Если вы покупаете игру с одного из коммерческих сайтов, то отсылаете по указанному на сайте номеру SMS, в котором сообщаете код программы, указанный на сайте. После этого вам на телефон придет ссылка, по которой можно скачать купленную вами программу. Единственная проблема WAP-сервиса - это высокая цена соединения, поскольку оплата происходит поминутно, а платите вы практически как за минуту разговора по телефону. Это получается весьма дорогое удовольствие. Отчасти эту проблему решает протокол GPRS.
1.7. Протокол GPRS Связь телефона по протоколу GPRS (General Packet Radio Service - радио сервис пакетной передачи данных) осуществляется в куда более щадящем режиме. Используя соединение WAP, вы фактически звоните по другому номеру, занимая тем самым один из многочисленных каналов связи, поэтому и оплата взимается поминутно. С использованием GPRS оплата происходит только за количество скачанных данных, измеряемое в байтах, килобайтах или мегабайтах. Например, оператор мобильной связи Би Лайн за один мегабайт изымает б рублей 60 копеек с вашего счета (по состоянию на 2004 год). Лучше использовать WAP соединение, то есть просматривать WAP-сайты, через протокол GPRS, значительно экономя средства. Все это происходит благодаря тому, что GPRS использует пакетную передачу данных и не задействует какой-то конкретный канал связи, он вклинивается в свободные зоны различных каналов, передавая информацию в виде небольших пакетов. Скорость связи может доходить до 115 кбит/с, но полагаю, что таких показателей никто не видел, а вот цифра в 3040 кбит/с вполне реальна. Связь через GPRS можно использовать и на компьютере, для выхода в Интернет через мобильный телефон. Такая услуга связи носит название мобильный Интернет.
Карта SIM
1.8. Карта SIM После приобретения телефона необходимо позаботиться о покупке SIM-карты одного из операторов мобильной связи. Купив SIM-карту, вы становитесь полноценным абонентом выбранного вами оператора связи. Сама SIM-карта выполнена в виде небольшого по размерам пластмассового прямоугольника, с контактной полосой на поверхности для стыковки с идентичным разъемом на телефоне. Каждая SIM-карта, содержит свой уникальный идентификационный номер, что в конечном итоге решает проблему одинаковых номеров. В SIM-карте также находится простейший процессор, и вы можете сохранять на SIM-карте записи, как правило, это обычная телефонная книга, примерно на 200-300 записей. Более подробно об установке SIM-карты в телефон и другой информации можно узнать из инструкции к вашему телефону. Таким образом, устройство мобильного телефона отдаленно напоминает устройство .компьютерных систем. Поэтому адаптация платформы Java 2 ME, для телефонов, произошла абсолютно безболезненно, переведя виток развития мобильной индустрии на новый, до настоящего времени не ведомый уровень. Следующая глава раскрывает теорию строения платформы Java 2 Micro Edition.
Глава 2. Платформа Java 2 Micro Edition Прежде чем мы приступим к знакомству с платформой Java 2 ME, следует определиться с основами программирования на Java. Эта и все дальнейшие главы рассчитаны на пользователя, имеющего самые минимальные представления о языке программирования Java. Если вы не относите себя к таковым, то перейдите в конец книги к приложению 1 и ознакомьтесь с основами языка Java. Информации присутствующей в приложении, будет достаточно для прочтения этой книги. История языка программирования Java насчитывает более десяти лет. Вначале, при создании Java, планировалось использовать этот язык для программирования микроконтроллеров бытовых устройств. Поэтому язык Java, тогда он, правда, имел другое название, изначально создавался независимым от архитектуры, компактным и безопасным, что в последствии сыграло решающую роль в его широком распространении. Однако, в тот момент язык программирования Java не смог обрести популярности. Более того, он оказался совершенно невостребованным. И только благодаря появлению сети World Wide Web, язык программирования Java получил настоящее признание, но уже в сфере Интернетпрограммирования. За этот десяток лет компанией Sun Microsystems было создано.несколько платформ для различных сфер деятельности. Q Java 2 Enterprise Edition - эта платформа необходима при создании серверных приложений; Q Java 2 Standard Edition - используется для работы на простых компьютерных системах; Q Java 2 Micro Edition — ориентирована на работу с портативными устройствами. Все три платформы занимают свои ниши и решают круг определенных задач. Но если платформы Java 2 ЕЕ и Java 2 SE испытывают жесткую конкуренцию в своем секторе рынка со стороны других технологий, то Java 2 ME находится вне конкуренции и является фактически стандартом в разработке программ для портативных устройств. Можно с уверенностью сказать: то, для чего изначально создавался язык программирования Java, а именно, создание программ для бытовых устройств, в итоге и стало его стихией. Так что такое платформа Java 2 ME, для чего она нужна и как устроена? На эти и другие вопросы мы попытаемся дать ответ в этой главе. Язык программирования Java независим от архитектуры, в силу того, что используется интерпретатор, переводящий байт-код, сгенерированный компилятором в машинно-независимый код. Интерпретация кода осуществляется под управлением системы выполнения, носящей название виртуальная Java машина. Такой механизм образует среду исполнения приложений. Среда исполнения,
Платформа Java 2 Micro Edition
)
в свою очередь, предъявляет определенные требования к свойствам языка программирования Java, построенные на основе спецификации Java Language Specification, разработанной компанией Sun Microsystems. При написании программ на Java активно используются библиотека Java API, без которых написать приложение практически невозможно. Библиотека Java API содержит огромное количество предопределенных интерфейсов, классов, методов, констант помогающих программисту в минимальные сроки создавать рабочее приложение. Подобный механизм создания и выполнения программ характерен для всех трех имеющихся платформ Java 2 ЕЕ, Java 2 SE и Java 2 ME. Платформы Java 2 ЕЕ и Java 2 SE можно признать почти одинаковыми, однако Java 2 ЕЕ несколько мощнее и содержит ряд библиотек позволяющих производить разработку программного обеспечения для серверов, а вот платформа Java 2 ME ориентирована именно на работу с портативными устройствами. В связи с этим Java 2 ME предъявляет уже свои требования к виртуальной Java машине, свойствам языка Java и библиотекам, поскольку системные ресурсы портативных устройств ограничены в силу своей спецификации аппаратного обеспечения. Небольшие размеры портативных устройств накладывают значительные ограничения на процессор, память, дисплей, устройство ввода, но платформа Java 2 ME разработана специально для того, чтобы' создавать программы, ориентированные именно на такие портативные устройства. Среда исполнения приложений Java, должна находиться внутри портативных устройств. За это отвечает их производитель, и это как раз и характеризует конкретное устройство, как устройство, поддерживающее технологию Java. Количество портативных устройств поддерживающих Java достаточно большое, но мощность и, соответственно, возможности устройств различны. Поэтому платформа Java 2 ME разработана в виде блочной модели надстраиваемых модулей, конфигураций и профилей. Конфигурация определяет свойства языка Java и виртуальной Java машины, а также набор доступных библиотек Java API. Профиль в свою очередь предъявляет требования к аппаратной части устройства и может содержать ряд дополнительных библиотек Java, направленных на работу с конкретным портативным устройством. Платформа Java 2 ME состоит из двух конфигураций: CDC (Connected Device Configuration - конфигурация подключаемых устройств) и CLDC (Connected Limited Device Configuration - конфигурация подключаемых устройств с ограничениями). Каждая из конфигураций определяетчсвое семейство портативных устройств. При программировании мобильных телефонов используется конфигурация CLDC. Каждая из конфигураций содержит свои профили, которые надстраиваются над своей конкретной конфигурацией. Когда программист создает программное обеспечение для портативных устройств, он обязан четко осознавать под какой профиль и конфигурацию он пишет программу, а производитель устройства должен осуществить поддержку того или иного профиля в связке со своей конфигурацией. Как программист вы не можете повлиять на сущность профилей и конфигураций - это жестко заданные спецификации, используемые в программировании
Платформа Java 2 Micro Edition портативных устройств. При создании программ вы будете ориентироваться на профиль, устанавливающий требования к аппаратной части устройства. На рис. 2.1 представлена общая схема модульного построения платформы Java 2 ME.
Платформа Java 2 ME
Платформа Java 2 SE
Платформа Java 2 ЕЕ
I
ч
[
Personal профиль Foundation профиль
]
Профиль MIDP
^
Конфигурация CDC Г
I
Виртуальная Java Машина
Виртуальная Java Машина
[
ч
Виртуальная Java Машина
Конфигурация ' CLDC
(
Килобайт Java машина
V
^
Рис. 2.1. Блочная схема построения платформы Java 2 ME Специально следить за свойствами конфигураций и профиля вам не придется. При создании проекта, в любой среде.программирования, появляется одно или несколько диалоговых окон, в которых посредством галочек или кнопок, в зависимости от реализации, избирается профиль и конфигурация. После чего вам автоматически будет предоставлен доступный набор свойств и средств выбранных профиля и конфигурации. Цель этой книги научить вас создавать приложения для мобильных телефонов с применением конфигурации CLDC и профиля MIDP. Вся концепция книги построена на использовании связки MIDP/CLDC, но несколько слов стоит сказать о конфигурации CDC и доступных для этой конфигурации профилях.
2.1. Конфигурация CDC Конфигурация CDC объединяет в себе ряд устройств имеющих постоянное сетевое соединение, таких как двунаправленные пейджеры, телевизионные приставки, автомобильные системы навигации, интеллектуальные коммуникаторы. Данные устройства характеризуются более мощными системными ресурсами, они имеют обычно 16 или 32-разрядные процессоры и как минимум 2 мегабайт памяти. В этой связи обе конфигурации CDC и CLDC, имеют свой набор свойств, определяющих поддержку библиотек Java API, виртуальную машину, свойства самого языка Java. Эти свойства и отличают разные конфигурации. Как вы уже знаете, каждая из конфигураций построена на основе блочной схемы в виде надстраиваемых профилей. Профиль ставит определенные требования к аппаратной части устройства, и содержит свой набор API позволяющий создавать на основе имеющихся библиотек различные приложения. Профили
Конфигурация CLDC созданы для определенной конфигурации, а приложения пишутся под конкретный профиль. Такая блочная модель позволяет любому приложению работать на портативных устройствах, поддерживающих данный профиль. Конфигурация может содержать несколько профилей. Конфигурация CDC имеет два профиля - это Foundation Profile и Personal Profile и PDA. Смысл и устройство этих профилей мы рассматривать не будем, они не имеют никакого отношения к теме этой книги и были приведены лишь для понимания общей идеи конфигурации. При желании в документации по Java 2 ME вы сможете найти необходимую информацию и изучите ее самостоятельно.
2.2. Конфигурация CLDC Конфигурация CLDC рассчитана на семейство мобильных устройств, таких как телефоны, органайзеры, КПК. Мобильные устройства, для которых предназначена конфигурация CLDC, характеризуются следующими параметрами: G процессор!6 или 32-разрядный; G память от 160 до 512 килобайт, для всей платформы Java 2 ME; Q беспроводное сетевое соединение; О питание от аккумуляторов. Все перечисленные характеристики, несомненно, накладывает определенные ограничения на создаваемое приложение. Конфигурации CDC и CLDC независимы друг от друга и не могут использоваться вместе. Вся концепция конфигурации CLDC была разработана дочерней группой Java Community Process, компании Sun Microsystems, которая включает в себя множество известных компаний: Q America Online; Q Bull; О Ericsson; G Fujitsu; Q Matsushita; Q Mitsubishi; G Motorola; a Nokia; 0 NTT DoCoMo; Q Oracle; G Palm Computing; a RIM; G Samsung; 01 Sharp; G Siemens; G Sony; G Sun Microsystems; G Symbian. Конфигурация CLDC содержит ряд классов, интерфейсов, методов платформы Java 2 SE, но в урезанном виде. Это и не мудрено, компьютерная платформа
I l l l i l
Платформа Java 2 Micro Edition
превосходит по мощности мобильные телефоны во много раз. С другой стороны,, та простота, с которой можно за несколько недель создать среднее по сложности приложение, подкупает и даже возвращает нас во времена шестнадцатибитных приставок. На самом деле общая масса игр, написанных на Java 2 ME, по своему игровому процессу напоминает именно те старые добрые времена. Конфигурация CLDC также определяется своим набором свойств состоящих из языка Java, виртуальной Java машины и библиотек API. В данный момент имеется две версии этой конфигурации - это CLDC 1.0 и CLDC 1.1. Конфигурация CLDC 1.1 имеет больше возможностей, например поддержку чисел с плавающей точкой, что соответственно предъявляет более серьезные требования к аппаратной части телефона. В момент написания книги таких телефонов не было, поэтому вся книга построена на конфигурации CLDC 1.0. К слову сказать, конфигурация CLDC 1.1 построена на первой версии и просто имеет ряд улучшений. Остановимся на каждом свойстве конфигурации CLDC 1.0 подробней. В последствии при упоминании конфигурации, будет иметься в виду CLDC 1.0.
2.2.1. Свойства языка Java Все свойства языка Java в конфигурации CLDC должны, насколько это возможно, соответствовать спецификации языка Java, но в силу ограниченности системных ресурсов мобильных устройств, не поддерживаются следующие свойства доступные в платформах Java 2 ЕЕ и Java 2 SE: 1) операции с дробными числами (floating point); 2) финализация (finalization); 3) отсутствует восстановление ошибок после сбоя (error handling).
2.2.2. Виртуальная машина Виртуальная машина, используемая в конфигурации CLDC, несколько отличается от обычной виртуальной машины задействованной в Java, но обязана оставаться совместимой со спецификацией этой виртуальной машины (Java Virtual Machine Specification). Виртуальная машина находится непосредственно в телефоне и за совместимостью с общепринятой спецификацией обязаны следить производители мобильных телефонов. Сама же виртуальная машина носит название Kilobyte Virtual Machine (KVM) из-за своей компактности и также имеет ряд недоступных свойств: 1) не поддерживаются операции с дробными числами (floating point); 2) нельзя создать класс загрузчик (class loader); 3) отсутствует механизм отражения (reflection); 4) не реализован Java Nativ интерфейс (Java Native Interface); 5) не поддерживается финализация (finalization); 6) отсутствует восстановление ошибок после сбоя (error handling); 7) не поддерживается работа с групповыми потоками (Thread group). Эти недоступные свойства языка Java и виртуальной Java машины, очевидным образом накладывают ощутимые ограничения на создаваемые программы,
Профиль к сожалению, архитектура аппаратной части телефонов, еще пока не в силах выдержать столь высокую нагрузку и поэтому от перечисленных выше свойств пришлось отказаться. ( . . '
2.3. Профиль
Как уже не раз отмечалось, профиль содержит предопределенные требования к аппаратной части устройства, а так же включает в себя минимальный набор API используемый в программировании мобильных устройств. Единственно доступный рабочий профиль в конфигурации CLDC имеет название MIDP (Mobile Information Device Profile - информационный профиль мобильных устройств). Спецификация профиля разработана экспертной группой MIDP Expert Group, в состав которой входят следующие компании: Q America Online; a DDI; Q Ericsson; Q Espial Group, Inc.; Q Fujitsu; Q Hitachi; Q J-Phone; Q Matsushita; Q Mitsubishi; 'Q Motorola, Inc.; Q NEC; Q Nokia; Q NTT DoCoMo; a Palm; Q Research In Motion; Q Samsung; Q Sharp; Q Siemens; Q Sony; Q Sun Microsystems, Inc.; Q Symbian; , Q Telcordia Technologies. Профиль MIDP был создан специально для поддержки мобильных устройств и задает следующие технические характеристики для мобильных устройств: Q разрешение экрана минимум 96x54 пикселя с глубиной экрана минимум 1 бит; Q устройством ввода может быть клавиатура или сенсорный экран; Q 32 килобайта динамической памяти; Q 128 килобайт под компоненты MIDP; Q 8 килобайт для хранения постоянных данных; Q беспроводная сеть; Q питание от аккумулятора.
Платформа Java 2 Micro Edition Такое сочетание конфигурации и профиля CLDC/MIDP используется в программировании мобильных телефонов и будет основным сочетанием при рассмотрении примеров из книги. На данный момент профиль MIDP имеет две версии: MIDP 1.0 и MIDP 2.0. До последнего времени первая версия MIDP была основным профилем при создании приложений для телефонов. Все телефоны, поддерживающие Java, имеют совместимость с профилем MIDP 1.O. Этот профиль был сформирован при начальном создании платформы Java 2 ME и имеет в своем составе определенный набор API. С выходом профиля MIDP 2.0 добавилось ряд новых библиотек, значительно улучшающих создание приложений для мобильных телефонов. Но самое главное это то, что у него имеется полная совместимость с профилем MIDP 1.0. Профиль MIDP 2.0 содержит большое количество новых дополнительных библиотек, отсутствующих в составе MIDP 1.0, но при создании приложений под профиль MIDP 2.0, можно пользоваться библиотеками профиля MIDP 1.0. Если же вы пишите программу под профиль MIDP 1.0, то библиотеки профиля MIDP 2.0 вам будут недоступны. В книге будут рассмотрены оба профиля как единое целое. Подытожив все вышесказанное о профилях и конфигурациях необходимых для программирования мобильных телефонов, можно резюмировать: программный продукт создаваемый разработчиками ориентирован на конкретный профиль, который является, спецификацией устанавливающей определенные требования к "аппаратной части телефона, а также содержит дополнительные библиотеки. Каждый конкретный профиль надстраивается над своей и только ему доступной конфигурацией. Конфигурация предъявляет требования к виртуальной Java машине и свойствам языка Java, используемым в этой конфигурации. Далее идет плотное взаимодействие с аппаратным обеспечением телефона, "через имеющиеся сервисы, которые предоставляПрограммный продукт ются операционной системой либо прошивкой телефона. Благодаря такой цепочке взаимодействий, любое проJava Java приложения игры граммное обеспечение, написанное на Java под конкретный профиль, будет работать на телефоне с поддержкой Профиль Java. На рис. 2.2 хорошо прослеживается общая схема взаHIDP 2.0 имодействия приложения с мобильным телефоном. MIDP 1.0 Такая 'модульность в построении Java 2 ME дает неоКонфигурация граниченную возможность в модернизации всей платфорCLDC мы и написанию действительно аппаратно-независимого Свойства Виртуальная кода программы. Люди, знакомые с моей книгой «DirectX 9. языка " машина Уроки программирования на C++», обязательно найдут KVM Java много общего в подходе реализации двух платформ DiПрошивка или rectX и Java 2 ME. Оставшаяся часть этой главы целиком операционная система посвящена рассмотрению пакетов и классов доступных мобильного телефона Аппаратное обеспечение телефона
Рис 2.2. Схема взаимодействия приложений с аппаратным обеспечением телефона
Профиль MIDP и конфигурация CLDC в MIDP 2.0/CLDC 1.0. Будут затронуты практически все имеющиеся компоненты данного профиля и конфигурации.
2.4. Профиль MIDP 2.0 и конфигурация CLDC 1.0 Язык Java самый «библиотечный язык», такого количества продуманных классов, наверное, нет ни в одном языке программирования. С другой стороны, простота в использовании Java, по всей видимости, поспособствовала определенной популярности этого языка. С точки зрения программиста, обилие готовых классов гораздо упрощает разработку программного продукта, и что самое глав" ное, уменьшает сроки создания программ. Профиль MIDP2.0 и,конфигурация CLDC 1.0, содержит большое количество интерфейсов и классов, использование которых в программировании приложений, пожалуй, сможет удовлетворить любого разработчика. Часть классов было взято из Java 2 SE с некоторыми усечениями, а часть была специально написана под Java 2 ME. Вся библиотека доступная для профиля MIDP 2.0 и конфигурации CLDC 1.0, состоит из одиннадцати пакетов. По традиции каждый отвечает за свою определенную область. Q java.lang; D java.util; 1 О java.io; О javax.microedition.lcdui; Q javax.microedition.lcdui.game; Q javax.microedition.io; Q javax.microedition.media; Q javaximicroedition.media.control; Q javax.microedition.pki; Q javax.microedition.midlet; Q javax.microedition.rms. Все пакеты с префиксами javax.microedition.*, написаны специально для Java 2 ME профиля MIDP 2.0. Пакеты с префиксом Java.*, взяты из Java 2 SE версии 1.4, в урезанном виде, и имеет полную совместимость с оригиналом и определенны в конфигурации CLDC 1.0.
2.4.1 Пакет java.lang Этот пакет содержит системные классы или основы языка Java и исключения. Имеется также один единственный интерфейс Runnable. На рис. 2.3 изображена иерархия классов пакета java.lang. Рассмотрим имеющиеся компоненты пакета java.lang и дадим краткую характеристику каждому из них. Интерфейс: О Runnable - создает поток в приложении.
Платформа Java 2 Micro Edition 1
Boolean
1
1
Character
1
1
StringBuffer
Short Runtime
String
Thread
System
Throwable
Exception
Error ,
[
СО
я
•н
-r-t
со
ф
h-
ф
о> ф
э
нн
ш от
со СО
1 «
ф
г
а
0
<л о
0
о> ф
ф тз
с о
тН
0.
гН
о.
о •м
л
К- 1
1—1
CQ
1
13
СО
*
i
i
чН
о •м
со
' -М
i с о
с
О) 1-Н
t-H
с: 0 •н •м а. ш о ш 3s
Exception
со •о
О)
с о •м
t
i
Exceptior
0 •н
i
oundsExce
Ф е
i
RuntimeException
oundsExce
о
0
-н
Exceptio
Ф О
ш ф
ntExcepti
т-1
о
.xception
с о
i
i
ateExcepl
i
Out DfMpmnrv Frro
InstantiationException
dsExcept
ClassNotFoundException
!
InterruptedException
tateExcep
1
IllegalAc6essException
izeExcept
VirtualMachineError
xception
'
1
Hath Long
Class
Byte
1
Integer
\_ •iс-»
О
Z
со
Рис2.3. Иерархия классов пакета java.lang Классы: Q Boolean - объектно-ориентированный класс, оболочка или как еще говорят «обвертка», для простого типа Boolean; Q Byte - объектно-ориентированный класс для простого типа Byte; О Character - объектно-ориентированный класс для простого типа Char; О C l a s s - виртуальная машина создает объекты этого класса, которые представляют интерфейсы и классы языка Java; Q Integer - объектно-ориентированный класс для простого типа int; О Long - объектно-ориентированный класс, оболочка для простого типа; Q Math - класс, содержащий математические методы; Q Object - суперкласс для всех классов Java. Все классы наследуются от класса Obj ect и являются его подклассами; Q Runtime - класс времени исполнения; Q Short - объектно-ориентированный класс, оболочка для простого типа Short; . Q String — создает строки символов; О S t r i n g B u f f e r - содержит строку символов любого размера;
Профиль MIDP и конфигурация CLDC О System - содержит ряд системных методов; О Thread - создает поток в работе приложения; О Throwable - суперкласс для всех подклассов, предназначенных для работы с ошибками и исключениями. Исключения: О Exceptions - исключения для классов и подклассов; Q ArithmeticException - арифметическое исключение; Q Ar ray IndexOutOf Bounds Except ion - исключение обрабатывающее неправильный индекс в массиве данных; Q ArrayStoreException - исключение обрабатывающее неправильноi заданный тип объекта в массиве объектов; Q ClassCastException - неправильно указан подкласс объекта; Q ClassNotFoundException - класс не найден; О IllegalAccessException - нет доступа к классу; Q IllegalArgumentException - указан неправильный аргумент;. Q IllegalMonitorStateException - мониторинг объектов; Q IllegalStateException — неправильно вызванный метод; О IllegalThreadStateException — неправильные установки потока; ч G IndexOutOf BoundsException - исключает неверный указанный индекс; Q InstantiationException - исключает ситуацию в создании или вызове членов абстрактного класса; Q interruptedException - исключает прерывание потока находящегося в состоянии ожидания: Q NegativeArraySizeException - исключает ситуацию в создании большего размера массива данных, чем было указано при инициализации; О NumberFormatException - неправильное преобразование строки в целочисленный тип данных; Q RuntimeException - суперкласс исключений времени исполнения виртуальной машины Java; О SecurityException - менеджер безопасности; Q StringlndexOutOf BoundsException - выход индекса за приделы строки. Ошибки: О Error.— обобщенная модель ошибок; Q OutOfMemoryError - ошибки связанные с выходом за пределы памяти; Q VirtualMachineError - ошибка времени исполнения.
2.4.2. Пакет Java, util В этом пакете содержатся классы стандартных утилит упрощающих работу программиста. Пакет сильно урезан по сравнению со стандартным пакетом Java 2 SE. На рис. 2.4 представлена иерархия классов пакета Java.util. Интерфейс: Q Enumeration - декларирует возможность доступа к элементам.
Платформа Java 2 Micro Edition
EnptyStackException
NoSuchElement Exception
Рис 2. 4. Иерархия классов пакета Java, util Классы: О Calendar - выполняя функции обыкновенного календаря; Q Date - реализует возможность работы с датой и временем; Q Hashtable - имеет возможность в сохранении объектов с доступом к ним по определенно заданному ключу; Q Random - генератор случайных чисел; О Stack - реализует функциональность стека; Q Timer — реализует возможность работы со временем; Ul TimerTask - планировщик задач; О Time Zone - дает возможность в определении временного пояса; О V e c t o r - класс для создания и содержания массивов любого размера. Имеет возможность изменять размер заданного массива. Исключения: G Empty StackExcept ion - указывает на пустой стек; Q NoSuchElementException - исключение указывает на отсутствие элементов в определенном перечислении.
2.4.3. ПакетJava, io Классы этого пакета отвечают за работу с входными и выходными потоками данных. На рис. 2.5 показана иерархия наследования классов пакета java.io. Интерфейсы: Q Datalnput — декларирует методы для чтения простых типов во входной поток данных; Q DataOutput - декларирует методы для записи простых типов в выходной поток данных. Классы: . Q ByteArraylnputStream - необходим при чтении входного потока байт из массива данных, для дальнейшего размещения их в памяти;
Профиль MIDP и конфигурация CLDC Object
ByteArraylnputstream
E CO CO
£ •H Э
Q. С HH CO
•H «0 о
i
i
l InputStream i — _t_ 1
OutputStream
Reader
•L
—I-
E cd ш u •H CO •H 3 ex +-*
3 О
>.
s cd O> -•H CO •M Э CL •H
E
cd
OJ
•4->
cd о
>4
т
4->
i i
lOException
-M CO
3 о cd
CD
1
i Writer
InputStreamReader Exception OutputStrearaWriter
CO l_ l_
з
1 Throwable
4-»
cz
-гЧ
EOFException
a.
UnsupportedEncodingExceptior
InterruptedloException JTSOataFormatException
Рис 2.5. Иерархия пакета Java.io Q ByteArrayOutputStream - необходим при записи потока байт из памяти в массив выходных данных; Q DatalnputStream- этот класс должен наследоваться от интерфейса Datalnput, реализуя при этом все его методы; О DataOutputStream - класс должен наследоваться от интерфейса DataOutput, реализуя при этом все его методы; Q InputStream - абстрактный класс, предназначенный для работы с входным потоком байтов; Q InputStreamReader — наследуется от класса Reader, реализуя методы для чтения символьных данных входного потока с перекодировкой; Q OutputStream - абстрактный класс, предназначенный для работы с выходным потоком байт; , Q OutputStreamWriter -наследуется от класса Writer, реализуя методы для записи символьных данных в выходной поток с перекодировкой; О PrintStream - расширяет выходной поток способностью печати данных; Q Reader - абстрактный класс, предназначенный для чтения символьных данных входного потока; Q W r i t e r - абстрактный класс, предназначенный для записи символьных данных в выходной поток. Исключения: Q EOFException - сигнализирует о конце файла; Q InterruptedloException - сигнализирует о прерванном действии по вводу выводу; Q lOException - указывает на исключение вывода вывода; Q UnsupportedEncodingException - указывает на невозможность перекодировки; Q UTFDataFormatException - сигнализирует о прочтении строки формата UTF-8.
Платформа Java 2 Micro Edition 2.4.4. Пакет javax. microedition. io Этот пакет содержит множество интерфейсов и всего два класса обеспечивающих связь с сетью. На рис. 2,6 и рис. 2.7 приводится общая схема наследования соответственно интерфейсов и классов пакета javax.microedition.io. Интерфейсы: Q CommConnection - находит последовательный порт; Q Connection - общий тип всей связи сети; Connection
t
t
1
1
с о •l-t о
CD О СО
0
Ч-»'
О1
о
и
0
ф с с о со о о
1
CD
о со ф о со
ф с с о со о. -и зг
0
о
с=
CD
о 0 0
ex
со
о,
со
t с
-гН
ш
1
0
о
- -гЧ
о со Ё СО ф
5
с
со
о со
0 0_ 0
с
•н
CD
£
1
с
0)
о
с о с о о.
=
1
1 с о
с: с=
0 0
Е СО
ф
ф с: с: о со •н
ф
со ф
О
0
CD
о со
с с
0
ф со
с о
о ф с с о
о е е о о
t
ф о со ф
о о
0
с о
0
о
с
ф cz с о со о. 3=
с:
0
о.
ж
Datagram
со ф
0
1
с о
Datagram
о ф с: о о •н ф
ф со
со
с: о
Datalnput DataOutput Securitylnfo
,
t с: о
е о
CD
ф с о со ш
cz с о со Ч-» ф .м о о со
•
о со
Рис 2.6. Иерархия интерфейсов пакета javax.microedition.io
PushRegistry
Thorwable
ConneotionNotFoundExoeption Рис 2.7. Иерархия классов пакета javax.microedition.io
Профиль MIDP и конфигурация CLDC Q Q G О Q
ContentConnection - находит связь с потоком; Datagram - общий интерфейс дейтаграммы; DatagramConnection - определяет возможность связи дейтограммы; HttpConnection - декларирует методы константы для http-соединения; HttpsCo,nnection - декларирует методы константы для безопасного http-соединения; Q InputConnection - интерфейс для создания входной связи с сетью; Q OutputCpnnection - интерфейс для создания выходной связи с сетью; Q SecureConnection - определяет безопасную связь с сетью; Q Securitylnf о - располагает методами для получения информации сетевой связи; Q ServerSocketConnection - реализует связь с сервером; Q SocketConnection - находит socket (сокет) для потока связи; Q StreamConnection'— связь с потоком; Q StreamConnectionNotif ier - определяет возможность всей связи; Q UDPDatagramConnection — реализует связь с дейтограммой. Классы: Q Connector - класс для создания объектов связи; О PushRegistry - класс для поддержания списков связей. Исключение: О ConnectionNotFoundException — указывает на отсутствие связи.
2.4.5. Пакет javax.microedition.lcdui Данный пакет имеет разнообразные классы для реализации пользовательского интерфейса в мобильных приложениях. Существует большое количество классов, благодаря которым можно создать действительно красивое интерактивное приложение. На рис. 2.8 изображена иерархия классов пакета javax.microedition.lcdui. Интерфейсы: О Choice — содержит набор библиотек создающих возможность выбора заданных элементов; Object
;
Command
Display
1
Displayable ,
1
Font
,' '
Canvas Screen
*.
i
i
Alert Form
i
t
List
TextBox
Graphics i
i £
Б •!->•
H • О +J CO =3 О
Image
Item Imageltem U
l
Gauge
I
DateField -
1 AlertType
ihoiceGroup
•
Рис 2:8. Иерархия классов пакета javax.microedition.lcdui
r
Ticker i s
*•' (Л
td OL CO
9 l-> HI
Dl С
•M
CO
i T3
1— t 9 -r4
U. •H X CD 1—
Платформа Java 2 Micro Edition CommandListener - реализует возможность получения событий; ItemCommandListener - реализует возможность получения событий от объектов класса Item; О. ItemStateListener - используется при получении событий о состоянии объектов класса Item встроенных в Form. Классы: G Alert — этот класс необходим при создании уведомлений об ошибках либо информационных сообщений; Q AlertType — отображает тип ошибки; Q Canvas - абстрактный класс, обеспечивает графическую прорисовку различных элементов на экране телефона; Q ChoiceGro.up - встраиваемая группа выбираемых элементов. Интегрируется в класс Form, наследуется от класса Item и реализует интерфейс Choice; Q Command - инкапсулирует командные действия, при этом, не определяя фактические действия команды, а лишь содержит информацию; О Cusfcomltem- создает возможность в отображении новых графических элементов встроенных в класс Form; О DateField — класс представляющий работу с датой и временем. Интегрируется в класс Form, наследуется от класса Item; О Display - этот класс-диспетчер, отвечающий за экран телефона; Q Displayable - абстрактный класс, содержит иерархию классов пользовательского интерфейса; . Q Font - класс шрифтов; Q Form - этот класс создает пустую форму в которую в последствии, можно встраивать ряд классов задающих пользовательский интерфейс всего приложения; Q Gauge - показывает графическое течение процесса; Q Graphics - предоставляет возможность в рисовании на экране телефона; Q Image - класс, отвечающий за загрузку и отображение любых видов изображений формата PNG; D Imageltem — контейнер для загруженных в приложение изображений; Q Item - суперкласс, содержащий ряд классов для их дальнейшей интеграции в класс Form; Q List - создает список группы элементов; Q Screen - суперкласс для" всех высокоуровневых классов определяющих пользовательский интерфейс приложения; Q Spacer - создает заданное пространство на экране; О Stringltem - дает возможность в создании массивов строк; * Q Text Box - создает редактируемый текстовый контейнер; Q TextField- создает редактируемый текстовый контейнер, который встраивается в класс Form; Q Ticker - создает в приложении бегущую строку текста.
Профиль MIDP и конфигурация CLDC
2.4.6. Пакетjavax.microedition.lcdui.game Это новый игровой пакет добавлен в профиль MIDP 2.O. В состав пакета входит пять мощных и хорошо продуманных классов, с помощью которых можно достаточно легко создавать игры для мобильных устройств. На рис. 2.9 показана иерархия классов пакета javax.microedition.lcdui.game. Классы: Q GameCanvas абстрактный класс, содержащий основные элементы игрового интерфейса; Q Layer - абстрактный класс, отвечающий за уровни представляемые в игре; Q LayerManager - менеджер уровней; Рис 2.9. Иерархия классов пакета Sprite - создает анимационные фреймы; TiledLayer — отвечает за создание фоновых,изображений.
2.4.7. Пакетjavax.microedition.media Пакет добавлен в профиль MIDP 2.0 и служит для создания звукового сопровождения в приложении. Пакет разработан специальной экспертной группой (MMAPI Expert Group), в состав которой входят такие известные компании: О Nokia (Specification Lead); Q Aplix Corporation; О Beatnik, Inc.; И France Telecom; О Insignia Solutions; Q Mitsubishi Electric Corp.; LJ Motorola; Q Netdecisions Holdings United; Q NTT DoCoMo, Inc.; О Openwave Systems Inc.; Q PacketVideo Corporation; Q Philips; a Siemens AG ICM MP TI; Q Smart fusion; О Sun Microsystems, Inc.; Q SymbianLtd; Q Texas Instruments Inc.; Q Vodafone; Q Yamaha Corporation; Q Zucotto Wireless. - •
Платформа Java 2 Micro Edition В профиле MIDP 1.0 отсутствует возможность полноценной работы со з,вуком, и каждый из производителей предоставлял свои библиотеки для этих цеManager Throwable . лей. В профиле MIDP 2.0 такой необходимости уже ' нет и можно .воспользоваться любым необходимым классом и интерфейсом из пакета javax.microediException tion.media. На рис. 2.10 приводится наследование интерфейсов этого пакета. Интерфейсы: Q Control - осуществляет контроль над проРис 2.10. Иерархия цессами; интерфейсов из пакета Q" C o n t r o l l a b l e - осуществляет контроль над javax.microedition.media. объектами; О Player - реализует контроль над воспроизведением; Q PlayerListener - необходим для получения асинхронных событий принятых от проигрывателя. Классы: Q Manager - менеджер системных ресурсов. Исключение: Q MediaException - исключает ошибки в-работе методов этого пакета.
2.4.8. Пакет javax. microedition. media, control С помощью пакета javox.microedition.media.control определяется контроль над воспроизведением заданных звуковых данных. Это небольшой пакет, имеющий в своем составе всего два интерфейса, ToneControl VolumeControl а на рис. 2.11 дается схема наследования интерРис 2.11. Иерархия фейсов. интерфейсов пакета Интерфейсы: javax. microedition. media.control ' Q ToneControl - воспроизведение однотональных звуков; Q VolumeControl - регулирует громкость воспроизведения.
2.4.9. Пакет javax. microedition. midlet Сам по себе пакет небольшой, но он играет ключевую роль при создании приложений на Java 2 ME. С помощью этого пакета происходит связь между приложением и мобильным информационным профилем устройства (MIDP). Рисунок 2.12 отражает полную иерархию пакета javox.microedition.midlet. Класс: I О MIDlet - основной класс, программы должен наследовать класс MIDlet, для управления работой приложения. '
Профиль MIDP и конфигурация CLDC Исключение: О MIDletStateChangeException - исключает неправильную работу с классом MI Diet.
2.4.10. Пакет javax.microedition.pki Пакет javax.microedition.pki сертифицирует информацию для безопасной связи. Рисунок 2.13 содержит иерархию этого пакета. Интерфейс: О C e r t i f i c a t e - общий сертификат. Исключение: О Certif icateExcepti.cf- обобщенный вид ошибок, возникший при использовании данного сертификата. Object
_L
HIDlet \
Throwable
Throwable
Exception
Exception
lOException
:
MIDletStateChangeException
t CertificateException
Рис 2.12: Иерархия пакета javax.microedition. midlet
Рис 2.13. Иерархия пакета javax.microedition. pki
2.4.11. Пакет javax.microedition. rms Этот пакет предназначен для создания механизма хранения и извлечения данных из памяти устройства. Хранение и запись данных происходит на основе менеджера системной записи (Record Management System), что дает возможность удалять, добавлять, просматривать, изменять или составлять список всех имеющихся записей. Имеется один класс и несколько интерфейсов реализующих механизм сохранения и извлечения данных. На рис. 2.14 представлена иерархия пакета javax.microedition.rms. Интерфейсы: Q RecordComparator — осуществляет сравнение двух записей; Q RecordEnumeration - реализует двунаправленный список записи; Q RecordFilter - определяет различные совпадения в записях; Q RecordListener - прослеживает события записи данных. Класс: О RecordStore - производит запись данных.
Платформа Java 2 Micro Edition
RecordStore
Throwable
RecordStoreNotFoundExceptior RecordStoreFullException RecordStoreNotOpenException Рис 2.14. Иерархия пакета javax.microedition.rms Исключения: Q invalidRecordlDException - исключает запись данных в неправильно указанный адрес; О RecordStoreException — Индикатор ошибки записи данных; Q RecordStoreFullException- указывает на переполнение системных ресурсов для записи данных; О RecordStoreNotFoundException - показывает, что указанное место для записи данных не было обнаружено; Q RecordStoreNotOpenException - указывает на невозможность записи. В этой главе мы рассмотрели состав одиннадцати пакетов, давая краткую характеристику имеющимся интерфейсам, классам и исключениям. В конце книги в приложении 2, вы найдете справочник по Java 2 ME, где рассматриваются более подробно все составляющие CDLC/MIDP. В следующей главе будет изучены интегрированные средства разработки приложений, бесплатно предоставляемые компанией Sun Microsystems.
Глава 3. Средства разработки мобильных приложений В предыдущей главе вы познакомились с общей архитектурой платформы Java 2 ME, в этой главе вашему вниманию будут представлены две интегрированные среды для разработки мобильных приложений - это SUN ONE Studio 4 Mobile Edition и J2ME Wireless Toolkit 2.1. Обе среды распространяется бесплатно и разработаны в недрах компании Sun Microsystems. Данные инструментарии можно скачать с сайта самой компании, либо воспользоваться компакт-диском к книге, где в директории \SDK находятся оба продукта. Предлагаемые к изучению инструментарии, в отличие от других сред программирования, адаптированы именно для создания приложений для мобильных устройств, поэтому будут рассмотрены и использованы в этой книге. Прежде чем приступить к инсталляции SUN ONE Studio 4 Mobile Edition и J2ME Wireless Toolkit 2.1, необходимо установить набор инструментальных средств Java 2 SDK, SE vl.4.2_03 (Software Development Toolkit Standard Edition). Это последняя на данный момент версия библиотеки, предоставляющая программные средства для создания приложений на Java. В состав этой библиотеки также входит Java 2 Runtime Environment, SE vl.4.2_03, которая необходима для работы приложений написанных на Java.
3.1. Установка Java 2 SDK SE Двойной щелчок левой кнопки мышки на файле j2sdk-l_4_2_03-windowsi586-p из каталога \SDK, находящегося на компакт диске, приведет к'распаковке архива. Далее появится окно с лицензионным соглашением, нажав на кнопку Next, вы попадете в окно Java 2 SDK SE vl.4.2_03 - Custom Setup, изображенное на рис. 3.1. В этом диалоговом окне вам будет предложено выбрать каталог и тип установки. Нам нужны все компоненты, поэтому нажмите кнопку Next. В следующем окне вам необходимо выбрать браузер для интеграции Java, остановите свой выбор на необходимом и подтвердите свои действия, после чего начнется процесс установки, в конце которого вам предложат перезагрузить компьютер. После установки Java 2 SDK, можно приступать к инсталляции SUN ONE Studio 4 Mobile Edition и J2ME Wireless Toolkit. Сразу хотелось бы остановиться на некоторых особенностях возникающих при инсталляции. Обе среДы программирования независимы друг от друга, но в составе, а точнее в комплекте с SUN ONE Studio 4 Mobile Edition, входит J2ME Wireless Toolkit версии 1.0.4 01, но на данный момент уже имеется J2ME Wireless
Средства разработки мобильных приложений
Custom Setup Select the program features you want installed. Select optional features to install from the list below. You can change your choice of features after installation by using the Add/Remove Programs utility in the Control Panel Feature Description ••;•
еэ ;g^|T
Demos
The Java 2 SDK, SE vl.4.2_03, including private j2rel.4.2jTO. This will require 120 MB on your, hard drive.
Source Code t Public Java Runtime Environment
Install to: C:y2sdkl.4.2JD3\
Change..
Next >
Cancel
Рис. З.7. Окно Java 2 SDK, SE v1.4.2_03-Custom Setup Toolkit версии 2.1. Такая путаница обусловлена как раз тем, что оба продукта независимы друг от друга и развиваются параллельно. Начнем установку с более мощной среды SUN ONE Studio 4 Mobile Edition.
3.2. Среда программирования SUN ONE Studio 4 Mobile Edition На компакт-диске в директории \SDK находится файл ffj_me_win32 - это программа установки интегрированной среды разработки SUN ONE Studio 4 Mobile Edition. После двойного нажатия левой кнопки мыши на этом файле, вы увидите окно с приветствием, нажав на кнопку Next, вы попадете в окошко с лицензионным соглашением. Ознакомившись с соглашением и нажав на кнопку Next, на экране монитора появится диалоговое окно SUN ONE Studio 4 update 1, Mobile Edition Setup, изображенное на рис. 3.2. В этом и следующем окне необходимо определиться с директорией, в которой будет размещаться устанавливаемый инструментарий, после чего появится диалоговое окно, показанное на, рис. 3.3, где перечисляются компоненты установки. Путь, задающий директорию для установки SUN ONE Studio 4 Mobile Edition не должен содержать пробелов. Окно выбора компонентов содержит элементы для установки. Как видно из рис. 3.3 инсталлируется не только J2ME Wireless Toolkit, но и Java 2 Platform Micro Edition, которая также может поставляться отдельно и лежит на компактдиске в каталрге \SDK (в том случае если вы предпочитаете работать с командной строкой).
SUN ONE Studio 4 Mobile Edition •*» Sun ONE Studio 4 update 1, Mobile Edition Setup The installer has selected the following versions of the Java 2 SDK that can be used with the IDE. The recommended option is the Java 2 SDK, Standard Edition (J2SE SDK), v. 1.4.0 with the IDE. Choose from the versions of J2SE SDK listed below or click Browse to specify a different J2SE SDK, v. 1.3.1 or v. 1.4.0. Refer to the Getting Started Guide for instructions on installing the J2SE, v. 1.4.0 platform.
Sun™ ONE Studio
Java 2 SDK Home: C:\j2sdk1.4.2_03 List of Java 2 SDK versions (v. 1.3.1 andv. 1.4.0) C:tj2sdM.4.2_03 (v. 1.4.2_03)
< Back
Next >
Cancel
Рис. З.2. Окно SUN ONE Studio 4 update 1, Mobile Edition Setup
'•* Sun ONE Studio 4
on Setup Select the components ofSun ONE Studio 4 update 1 that you want to install. Some components cannot be deselected if they are required by other components that are selected to be installed. •/ Core Platform & Modules
Sun-ONE Studio
,/ Java 2 Platform Micro Edition (J2ME), Wireless Toolkit 10.4
Denotes that the component cannot be deselected and will be installed.
«Back
Г Nexf>
Рис. 3.3. Окно выбора компонентов к установке
]]
Cancel
Средства разработки мобильных приложений Два последующих окна носят скорее информационный характер, просто нажмите кнопку Next и мастер установки начнет свою работу по инсталляции среды программирования SUN ONE Studio 4 Mobile Edition на компьютер.
3.2.1. Настройка SUN ONE Studio 4 Mobile Edition После установки среды программирования SUN ONE Studio 4 Mobile Edition, на рабочем столе появится иконка быстрого старта. При первом вызове инструментария SUN ONE Studio 4 Mobile Edition, необходимо настроить некоторые параметры. В первом появившемся окне, изображенном на рис. 3.4 надо выбрать директорию, где будет располагаться ваш рабочий каталог, содержаEnter User Directory щий исходные коды создаваемых Type the name of the directory where you want thetDE to store your программ. settings and project information. For example, type CAide-userdir. Выберите любой устраивающий Be sure that the directory you choose is in a place that is always accessible on your system. If you have different versions of the IDE, вас каталог, или создайте новый use a different user directory for each IDE versioa и нажмите кнопку Next. СледуюThe name of this directory is stored in your Microsoft Windows Registry and is used every time you run the IDE. This directory щее окно, показанное на рис. 3.5, should be different than the directory where the IDE is installed. предложит сохранить настройки от |C:VJavaSourcesj предыдущих версий. Если у вас были установлены ранние версии SUN ONE Studio, воспользуйтесь этим мастером, есРис. З.4. Выбор рабочей директории ли нет, нажмите кнопку Finish. В сле-
need to import settings; ; lets you impott your iPc environment and settings from previous (serge-user mode) versions; •NetBean* (3.0 and 3.1 releases) ' '. ; Forte tor Java (2 0 and 3 0 releases) If your previous ЮЕ was installed n multi-user mode, cfick Cancel end see the'Sun ONE Studio Knowledge [3ase Do you wish to import settings from a previous arstaSaticn? !
Я j tip. Skip the settings import.: '.
.
.' .
О: Yes, please import my settings from the previous version fete: t is not possbte to import settings at a later ttn
Рис. З.5. Окно Setting Import Wizard
SUN ONE Studio 4 Mobile Edition дующем появившемся окне, показанном на рис. 3.6, будет предложено сконфигурировать установленную среду программирования при помощи мастера конфигурации.
Рис. 3.6. Окно Setup Wizard Настройка с помощью мастера Setup Wizard происходит в три этапа. На первом этапе, в окне, показанном на рис. 3.6, можно установить режим отображения инструментария, выбрать web-браузер, а также по необходимости задать используемый прокси сервер (Proxy Server). Задайте необходимые настройки и нажмите кнопку Next. Следующее диалоговое окно изображенное на рис. 3.7, показывает перечень инсталлируемых модулей. Настройки по умолчанию в этом окне целесообразно оставить без изменений Далее, нажав кнопку Next, вы попадете в последнее диалоговое окно Update Center, изображенное на рис. 3.8, с помощью которого можно обновить установленные компоненты через Интернет. Если вы имеете подключение в Интернет, то можно обновить некоторые из компонентов, процедура абсолютно бесплатна. Для отказа от обновления нажмите кнопку Finish. После чего перед вами появиться рабочая поверхность SUN ONE Studio 4 Mobile Edition, а на ее фоне окно Registration Wizard, показанное на рис. 3.9. С помощью этого окна необходимо зарегистрировать установленный продукт на сайте производителя. Рекомендую вам зарегистрировать этот инструментарий, тем более что это бесплатно и в будущем может принести вам немалую пользу, например обновление установленных компоне'нтов. После регистрации вы попадете непосред-
Средства разработки мобильных приложений
Modules S>
Backward Compatibility Data Files Debugging Distributed Application Support Editing
,
General Online Help
.
Infrastructure J2ME
Рис. З.7. Инсталлируемые модули
s Update Center i.J MetBeans Update_Ceriter Beta Г] 'NetBeans Update eerier Alpha
13'BunONE"studio''''-
;
Рис. З.8. Окно Update Center
ственно в главное окнр SUN ONE Studio 4 Mobile Edition, где перед вами появится диалоговое окно Welcome SUN ONE Studio 4 update 1, Mobile Edition, показанное на рис. 3.10,, благодаря которому можно создать проект или открыть необходимый файл.
Ш111
SUN ONE Studio 4 Mobile Edition noose to Create or edit Registration Registering the product wiH allow .
> -.ibout new products »icf product
Register usirjg the web c°» change regatrawn - necessary after swtehmglDc versions] Highfy recommended аз it pr^wtei there irjditwnal benefits' rnodufes andi^dales. ' - • - - . - . • : . . .-.:•> of Sun ОМЕ Sti-чИс, preview fitodiJes, patches and bug fixes through Ihe Early
- EntStemerits to Access progr
Register by Fax or maS (fil cud ^ t.:-c i'n and pt :nt it, !he:i Fax or гоаЙ О . Register Later
•'-
•
• • . - • '
',.:. Never Pegi^Jer
Serial Nuieer:
set™ пшюег Is reoufreti by ilns prociuci
Рис. З.9. Окно Registration Wizard
I Welcome to Sun ONE Studio 4 update 1, Mobile Edition
To get started, choose a task below. ® Sun Ore Studio Web Resources
Create a new Forte object, for example: • A MIDlet
Si Open File... :
• A MIDlet Suite • A Java Class Or, select from the complete set of object templates.
Tip of the Day S Next Tip ^ Previous Tip
You can also update modules in the IDE without having to connect to an Update Center server. Manually download the NBM file of the module you want to update. Then choose Tools > Update Center and select the Install Manually Downloaded Modules radio button in the fit-et r,yno r,f tKa tln-yatvl
.
„
.
.
_
Show Welcome Screen on Startup
Рис. 3.10. Окно Welcome SUN ONE Studio 4 update 1, Mobile Edition
•
j Средства разработки мобильных приложений С помощью окна Welcome можно осуществить так называемый быстрый старт, выбрав необходимое действие. По размеру окно довольно таки большое и разделено на две части. В его нижней области имеется возможность отключения появления этого окна при открытии среды программирования SUN ONE Studio 4 Mobile Edition. Произведя таким образом настройку инструментария при первом старте, вы получите все рабочее окно SUN ONE Studio 4 Mobile Edition, изображенное на рис. 3.11.
.le
;
Ed* vtew
Ргад^
Ы:!« :ло...,
v-^.-r-*v)
xtf
vwxtow Help
ii а э « *' •. :t а в ч у
Рис. 3.11. Рабочее окно SUN ONE Studio 4 Mobile Edition Главное'окно инструментария выполнено в лучших традициях подобных средств программирования, предоставляя большое количество разнообразных панелей инструментов, меню, кнопок, текстовых полей, а также'окно Explorer (обозреватель), которое находится с левой стороны рабочей поверхности SUN ONE Studio 4 Mobile Edition. Окно Explorer состоит из трех вкладок: Файловые системы, Выполнение и Javadoc. Они находятся в нижней части окна Explorer. Вкладка Файловые системы дает возможность подключить к проекту рабочую директорию, где, впоследствии, будут находиться исходные коды, то есть произвести монтаж файловой системы. Там же происходит подключение архивов Archive (JAR, Zip), о чем подробно будет рассказано в разделе 3.2.2. Во вкладке Выполнение можно подключить телефонные эмуляторы и следить за процессами отладки и выполнения программы.
SUN ONE Studio 4 Mobile Edition Вкладка Javadoc содержит сгенерированную документацию к проекту в виде HTML страниц. Линейка меню, в верхней части среды программирования SUN ONE Studio 4 Mobile Edition, содержит множевтво команд. Щелкнув мышью на одном из названий, откроется выпадающее меню, содержащее список новых команд. Некоторые команды имеют выпадающие подменю. Рассмотрим ряд основных комагад среды программирования SUN ONE Studio 4 Mobile Edition. Напротив каждой из команд в скобках находятся названия «горячих клавиш» для быстрой -рчботы с системой.
Меню File О New (Ctrl+N) - создает новый файл. U Mount Filesystem - осуществляет монтирование файловой системы1. О Uniriount Filesystem - удаляет файловую систему. Q Open File (Ctrl+O) - открывает файл. Q Save (Ctrl+S) - сохраняет открытый файл. , Q. Save All - сохраняет все открытые файлы. Q Print (Ctrl+P) - печать. Q Page Setup - предварительный просмотр. Q Exit - выход из SUN ONE Studio 4 Mobile Edition.
Меню Edit Q Q Q О Q Q Q а Q
Undo (Ctrl+Z) - возврат произведенной операции на шаг назад. Redo (Ctrl+Y) - переход к произведенной операции на шаг вперед. Cut (Ctrl+X) - вырезает часть кода, текста и так далее. Соре (Ctrl+C) - копирует информацию в буфер обмена. Paste (Ctrl+V) - вставка. Delete (Delete) - удаление информации. Find (Ctrl+F) - поиск. Replace (Ctrl+H) - повтор. Search Filesystem - поиск файловой системы.
Меню View Q Explore From Here (Ctrl+O) - открывает окно обозревателя в главном окне. Q Properties (Ctrl+1) - свойства файла. Q Explorer (Ctrl+2) - обозреватель. Q Source Editor (Ctrl+3) - текстовый редактор. Q Output Window (Ctrl+4) - окно вывода, показывает результат работы программы. О Debugger Window (Ctrl+5) - окно отладчика. Q Web Browser (Ctrl+7) - Интернет-браузер. О Javadoc Index Search (Shift+Fl) - поиск по индексу в документации. О Workspaces - рабочее окно.
Средства разработки мобильных приложений Меню Project О Project Manager (Ctrl+Shift+F9) - открывает окно менеджера проекта. О Compile Project (Ctrl+Shift+Fll) - компилирует весь проект. О Build Project (Ctrl+Shift+Fll) - компонует весь проект. О Set Project Main Class (Ctrl+Shift+M) - устанавливает выбранный файл с кодом — главным классом всей программы. Q Debug Project (Ctrl+Shift+F5) - отладчик проекта. Q Import Project - импортирует выбранный проект. Меню Build О Compile (F9) - компилирует выбранный файл. Q Compile All (Shift+F9) - компилирует все файлы проекта. Q Build (F11) - компонует выбранный файл. Q Build All (Shift+Fl 1) - компонует все файлы проекта. О Stop Compile (Alt+Shift+C) — остановка компиляции. Q Next Error (Fl2) - следующая ошибка. G Previous Error (Shift+F12) - предыдущая ошибка. Меню Debug Q Start (Alt+F5) - запуск откомпилированной программы. Q Finish (Shift+F5) - остановка работы программы. U Add Breakpoint (Ctrl+Shift+F8) - установка точки прерывания. Q Debugger Window (Ctrl+F5) - окно отладчика. Меню Help Q Contents - содержание справки. U Наборы Справок - открывает подменю с набором имеющихся справок.
3.2.2. Создание проекта в SUN ONE Studio 4 Mobile Edition Для создания проекта в среде SUN ONE Studio 4 Mobile Edition, необходимо выбрать в меню команду Project => Project Manager, в появившемся окне менеджера проектов изображенного на рис. 3.12, нажмите кнопку New. Вместо окна менеджера проектов появится небольшое диалоговое окно Create New Project, где в поле Project Name необходимо задать имя проекту, например Demo и нажать на кнопку ОК. После этих действий на экране появится окно конфигурации созданного проекта показанное на рис. 3.13. В окне конфигуратора проектов есть два пункта: Java 2 Standard Edition (J2SE) и Mobile Information Device Profile (CLDC\MIDP), выполненные в виде списка выбираемых элементов. Выбрав один из двух пунктов можно сконфигурировать проект для создания стандартной программы на Java 2 SE, либо приложение для мобильных телефонов если избрать пункт Mobile Infdrmation Device Profile (CLDC\MIDP). Выбираем пункт для создания мобильных приложений
SUN ONE Studio 4 Mobile Edition
Project Configuration {1 of 1) Choose a configuration for. this project J Java JL Standard Edition (JISE) : .. • »> Mobile Information Device Profile (CLQCAVD-'i The project configuration win affect the default con and code completion .for Java sources.'
Рис. 3.12. Окно менеджера проектов
Project Configuration (1 of 1)
Choose a configuration for thi? project. О Java 2 Standard Edition (J2SE) Ф Mobile Information Device Profile (CLLICWDP). The project configiiralion witl afiocf !he >:й fault "ornpiler. executor, debugger, and code completion for Java sources.
"Справка:
Рис. 3.13. Окно конфигуратора проекта
Средства разработки мобильных приложений и нажимаем кнопку Finish. После чего в нижней части окна Explorer, к вкладкам Файловые системы, Выполнение и Javadoc, добавится еще одна вкладка Project Local Drectory Demo. Затем необходимо произвести мон! 3 Archive (JAR, Zip) тирование файловой системы для сконфигурированного проекта. В нижней части окна Explorer, перейдите на вкладку Файловые системы и в появившемся окне нажмите правой кнопкой мыши на надписи Файловые системы. В ответ на эти действия появится череда выпадающих меню, выберите команду Mount => Archive (JAR, Zip), изображенную на рис. 3.14. Выбрав команду Archive (JAR, Zip), вы перейдете к окну New Wizard Archive (JAR, Zip), с помощью которого РисЗ. 14. Вкладка производится монтаж необходимой для Файловые системы проекта библиотеки Java API. Все библиотеки скомпонованы в виде архивов, например библиотека для профиля MIDP 1.0, содержится в архиве midpapi.zip. Ситуация здесь несколько запутанная. Как уже говорилось в состав инструментария SUN ONE Studio 4 Mobile Edition входит также среда J2ME Wireless Toolkit версии 1.0.4 01, содержащая архив API для профиля MIDP 1.0. На рис. 3.15 показано окно New Wizard 1 Explorer [Файловые системы] ;
Рис. 3.15, Окно New Wizard - Archive (JAR, Zip,)
'
SUN ONE Studio 4 Mobile Edition Archive (JAR, Zip) и подключаемый архив API, находящийся в папке lib среды J2ME Wireless Toolkit 1:0. При установке более поздней версии этой интегрированной среды вы сможете подключать API и для профиля MIDP 2.0, выбрав соответствующий файл из директории, в которую была установлена среда J2ME Wireless Toolkit 2.1 более поздней версии. Также существует возможность выбора и других API, предоставляемых конкретным производителем телефонов, в том случае, если вы желаете использовать библиотеку сторонних производителей. В следующей главе будет рассмотрена установка и настройка различных телефонных эмуляторов и программного обеспечения для программирования телефонов разнообразных марок. После монтирования файловой системы, необходимо также произвести монтаж директории, где будет содержаться .исходный код созданного проекта. Монтаж директории происходит по той же схеме, что и монтаж файловой системы, но в выпадающем меню нужно выбрать команду Mount => Local Directory и в появившемся окне New Wizard - Local Directory указать место, где будет храниться исходный код программы, поле чего нажмите кнопку Finish. Создав рабочий каталог для приложения, его необходимо добавить в проект. Нажмите правой кнопкой мыши на только что добавленной директории во вкладке Файловые системы окна Explorer и в появившемся меню выберете команду Tools => Add to Project. Для каждого нового создаваемого проекта, необходимо произвести все выше описанные действия из раздела 3.2.2.
3.2.3. Создание приложений в SUN ONE Studio 4 Mobile Edition Завершив создание проекта, можно переходить к написанию кода приложения. Для этого перейдите на закладку созданного проекта Demo, в окне Explorer и выберете команду меню File => New File, либо воспользуйтесь горячими клавишами Ctrl+N. На экране появится окно New Wizard, представленное на рис. 3.16, где происходит выбор шаблона создаваемого приложения. В качестве создаваемой демонстрационной программы произведем выбор шаблона HelloMIDlet, который формирует код простой программы, имеющей название мидлет и позиционирующейся в Java 2 ME как приложение, написанное специально для мобильного устройства. В главе 5 будет дано подробное объяснение сути мидлета. Нажав на кнопку Next, вы попадете в следующее окно New Wizard - HelloMIDlet, где необходимо указать будущую директорию нахождения мидлета и задать имя пакету, либо воспользоваться стандартным пакетом, предоставляемым по умолчанию. На рис. 3.17 показано окно New Wizard — HelloMIDlet с выбранной директорией и пакетом по умолчанию. Указав пакет и выбрав директорию, нажмите на кнопку Finish. После этого будет автоматически сгенерирован простейший код примера HelloMIDlet проекта Demo, который появится в текстовом редакторе Source Editor, с правой сторо-
Средства разработки мобильных приложений
Executable class which displays text on the screen of a device,
i
Рис. 3.16. Окно New Wizard
Рис. 3.17. Окно New Wizard - HelloMIDIet ны в свободном до этого времени пространстве главного окна среды SUN ONE / Studio 4 Mobile Edition, представленного на рис. 3.18. Работа с кодом в текстовом редакторе Source Editor, осуществляется обычным образом, характерным практически Для всех сред программирования.
SUN ONE Studio 4 Mobile Edition &Я Vfew Project Bw« Debug Versiorcng Tools
V*daw Help
javax.tticcoedmon.Kidlet.*; uit>ort Javax.aictoedition.Icdm.*;
lie claM HelloHIDlet extewta HIDlet inploexta CouandLlaunec | privttte Coesand exicCoMMand; ,
public display - Display sxitCommand • new C<eM*df"Exit", Сомали.SCREEN, 2);
Рис. 3.18. Окно проекта Demo
3.2.4. Компиляция и запуск программ в SUN ONE Studio 4 Mobile Edition
'
В результате всех вышеперечисленных действий вы получили код простого примера HelloMIDlet выводящего на экран телефона информационную надпись Test string. Но сначала необходимо откомпилировать и собрать программу. Для компиляции исходного кода выберете в меню команду Build => Compile или используйте «горячую» клавишу F9. Откомпилировав рассматриваемый пример, произведите кбмпоновку всего проекта путем выбора команды из меню Build => Build или нажмите клавишу F11. После этих действий у вас появится возможность запуска созданной программы на эмуляторе телефона предоставляемого средой программирования SUN ONE Studio 4 Mobile Edition. Для этого в меню выберете команду Debug =Ф Start или воспользуйтесь сочетанием клавиш Alt+F5. После запуска откомпилированной и скомпонованной программы на экране появится эмулятор телефона изображенный на рис. 3.19. Эмуляторы телефона, существующие в составе SUN ONE Studio 4 Mobile Edition, представлены встроенной средой программирования J2ME Wireless Toolkit 1.0. Имеется несколько эмуляторов мобильных устройств: ГД DefaultColorPhone - простой телефон с цветным дисплеем; Q DefaultGrayPhone - телефон с монохромным дисплеем; Q MinimumPhone - телефон с минимальными техническими характеристиками;
Средства разработки мобильных приложений G Motorola_i85s - эмулятор телефона i85s компании Motorola; Q PalmOS_Device - представляет устройство фирмы Palm; Q RIMJavaHandheld - представляет устройство фирмы Blackberry. Чтобы подключить любой эмулятор из имеющегося списка для тестирования разработанной программы, необходимо выбрать вкладку Выполнение в окне Explorer, нажав на футуристический ключ с левой стороны каталога Device Emulator Registry, раскрыв тем самым ветку дерева этого каталога, показанную на рис. 3.20. i Explorer [Выполнение] ; ^ Выполнение *• О Processes Debugger S& vcs Commands В> Device Emulator Registry 9 Э Default Emulators Ш> MIDP : J2ME Wireless Toolkit 1 .0.4,01 9 Installed Emulators J2MEVWeless Toolkit 1 .0.4JJ1 \ 0 DefaultColorPhone ] 0 DefauJGrayPhone jy MinimumPhone
1
В
PalmOS_Device RIMJavaHandheld
Рис. 3.20. Вкладка Выполнение окна Explorer
Рис. 3.19. Эмулятор телефона, демонстрирующий работу примера HelloMIDIet
Для того чтобы посмотреть доступные эмуляторы, откройте подкаталог Installed Emulators каталога Device Emulator Registry, нажав на ключик с левой стороны подкаталога. Раскрыв подкаталог Installed Emulators, вы увидите вложенную папку J2ME Wireless Toolkit 1.0, содержащую выше перечисленные в этом разделе эмуляторы. Для того чтобы выбрать эмулятор из папки J2ME Wireless Toolkit 1.0, щелкните правой кнопкой мыши на необходимом эмуляторе, например Motorola_i85s и в появившемся меню выберете команду Set As Default, назначив этот эмулятор текущим для данного проекта. Чтобы протестировать созданную программу на новом эмуляторе, запустите программу снова, выбрав в меню команду Debug => Start или используйте сочетание клавиш Alt+F5. На рис. 3.21 изображен эмулятор телефона i85s фирмы Motorola. Впоследствии при установке эмуляторов и средств программирования сторонних производителей, можно подключать новые эмуляторы в инструментарий
J2ME Wireless Toolkit 2.1 Рис. 3.21. Эмулятор телефона i85s SUN ONE Studio 4 Mobile Edition. Для этого необходимо выбрать вкладку Выполнение в окне Explorer и нажать на ключ с левой стороны каталога Device Emulator Registry раскрыв ветку дерева этого каталога и правой кнопкой мыши щелкнуть на подкаталоге Installed Emulators. В появившемся меню выберете команду Add emulators. Затем появится диалоговое окно Select emulator installation directory, где нужно указать директорию, в которой установлен необходимый эмулятор, и нажать на кнопку Add. Некоторые производители телефонов позаботились об интеграции своих программных продуктов в среду SUN ONE Studio 4 Mobile Edition и на начальном этапе установке этих средств, можно указать, желаете ли вы встроить устанавливаемую программу в SUN ONE Studio 4 Mobile Edition или нет. В следующей главе будут рассматриваться множество программ от различных производителей, где мы обязательно рассмотрим возможность добавления эмуляторов в среду программирования SUN ONE Studio 4 Mobile Edition.
3.3. Среда программирования J2ME Wireless Toolkit 2.1 Программный продукт J2ME Wireless Toolkit 2.1 компании Sun Microsystems распространяется бесплатно и представляет упрощенную среду программирования. Механизм работы J2ME Wireless Toolkit 2.1 очень прост: вы создаете проект, размещаете файлы исходного кода в директории J2ME Wireless Toolkit 2.1 и компилируете весь проект. Файлы исходного кода могут быть написаны в любом текстовом редакторе. Потом запускаете готовое приложение на эмуляторах доступных в этой среде программирования и тестируете созданную программу.
3.3.1. Установка J2ME Wireless Toolkit 2.1 На компакт-диске в папке \SDK находится файл j2me_wireless_toolkit-2_lwindows. Двойной щелчок на этом файле приведет вас в программу установки среды программирования/2М£ Wireless Toolkit. В первом появившемся окне программы установки Java Virtual Machine Location, показанном на рис. 3.22, необходимо указать путь в директорию, где у вас установлена виртуальная Java машина. Если при установке пакета Java 2 SDK SE, вы не изменяли директорию для виртуальной машины, то оставьте прописанный путь, указанный в окне программы установки Java Virtual Machine Location и нажмите кнопку Next. В следующем окне Choose Destination Location, изображенном на рис. 3.23, нужно выбрать место Для установки среды программирования J2ME Wireless Toolkit 2.1.
Средства разработки мобильных приложений
The Java 2 SDK, Standard Edition (1.4 or later) ' is instated on jiout machine at CA|2sdk1.4.2 03. Press 'Next' to install J2ME Wireless Toolkit 21 with this Java 2 SDK. or Browse' to locate another Java 2 SDK.
• Destination Folder Browse.
C:\j2sdk1.4:2J>3
< Back
Next>
Cancel
Рис. 3.22. Окно программы установки Java Virtual Machine Location
Choose Destination Location Select folder where Setup will install files. Setup will install J2ME Wireless Toolkit 21 in the following folder. To install to this folder, dick Next. To install to a different folder, click Browse and select another folder.
r Destination Folder Browse...
C:\WTK21
с Back
Next>
Cancel
Рис. 3.23. Окно Choose Destination Location При задании директории нельзя прописывать путь с пробелами, а лучше оставить директорию по умолчанию, выбранную программой установки, иначе в последствии у вас возникнет масса проблем при компиляции исходных кодов. Нажав на кнопку Next в окне Choose Destination Location, подождите конца установки среды программирования J2ME Wireless Toolkit 2.1.
J2ME Wireless Toolkit 2.1 После установки программы, зайдите в меню ПУСК => Все программы => J2ME Wireless Toolkit 2.1 => KToolbar и у вас на Экране появится рабочее окно J2ME Wireless Toolkit, показанное на рис. 3.24, где и происходит основная работа над проектами по созданию приложений для мобильных устройств.
Г-IIПIIX1
4 J2ME Wireless Toolkit ct
File J^J^ Help i % New Project... ^ Open Project
^ Clear Console
i Device: Create a new project or open an existing one
Рис. 3.24. Рабочее окно J2ME Wireless toolkit Линейка меню среды программирования J2ME Wireless Toolkit, содержит четыре команды, щелкните мышей на названии любой из команд и вы откроете выпадающее меню. Каждое из выпадающих меню содержит ряд команд, разберем основные из них. Меню File Q New Project - создает новый проект; О Open Project — открывает проект; Q Save Console - сохраняет информацию с консоли; Q Utilities - утилиты; О Exit - выход. Меню Edit l_l Preferences - свойства проекта; Q Clear Console - отчистить консоль.
Средства разработки мобильных приложений Меню Project Q Q Q Q Q Q
Build — компиляция проекта; Clean - закрывает открытый проект; Run - запуск откомпилированной программы; Package - упаковка-проекта; Debug - отладка; Settings - установки проекта.
3.3.2. Создание проекта в J2ME Wireless Toolkit 2.1 Рабочее окно среды J2ME Wireless Toolkit, выглядит на много проще чем SUN ONE Studio 4 Mobile Edition. Для создания нового проекта нажмите на панели инструментов кнопку New Project, либо выберете в меню команду File => New Project. В появившемся окне New Project, показанном на рис. 3.25, в поле Project Name дайте имя всему проекту, например Demo и в поле MIDlet Class Name, задайте название основному классу мидлета приложения.
Рис. 3.25. Окно New Project Чтобы было понятно, о чем идет речь, забегая вперед, поясню: мидлет в Java 2 ME - это вся программа в целом, а с основного класса мидлета начинается работа всего приложения. Поэтому названия данное в поле MIDlet Class Name должно соответствовать названию основного класса мидлета, нельзя не задавать название основному классу мидлет либо использовать несуществующее название, иначе при компиляции возникнет масса ошибок. В главе 5, вы найдете более подробное объяснение модели работы и построения программ в Java 2 ME. При знакомстве с инструментарием SUN ONE Studio 4 Mobile Edition, был создан проект Demo, основной класс мидлета имел название HelloMIDlet; воспользуемся этим исходным кодом и дадим название классу мидлета HelloMIDlet в поле MIDlet Class-Name, и нажмем после этого кнопку Create Project. Вслед за этим появится диалоговое окно Settings for project «Demo», показанное на рис. 3.26, где нужно произвести ряд установок для настройки нового проекта. Диалоговое окно Settings for project «Demo» разделено на семь вкладок, в каждой из которых можно задавать различные установки для создаваемого проекта. Первая вкладка API Selection, изображенная на рис. 3.26, позволяет задавать конфигурацию и профиль создаваемого проекта. И здесь необходимо быть аккуратным: если вы-планируете разрабатывать приложение только под профиль MIDP 1.0, то в поле Target Platform (выбор платформы), нужно указать соответствующий профиль.
;
J2ME Wireless Toolkit 2.1 j Settings for project "Demo" API Selection I Required J Optional J User Defined f MIDIets | Push Registry I Permissions; Target Platform
JJTW
Щ
J7WI
: JTW
Custgm ^3
rProfiles MIDP2.0
Configurations— © CLDC1.0 О CLDC 1.1 .Optional
-
Wireless Messaging API (JSR120) 0 Mobile Media API (JSR 135)
.-Additional APIs
:
—
П Web Service Access for J2M£ (JSR 172).
Рис. 3.26. Диалоговое окно Settings for project «Demo» Вторая вкладка Required (Атрибуты), изображенная на рис. 3.27, содержит мета информацию создаваемой программы в виде семи различных значений, которые можно устанавливать должным образом. Q MIDlet -Jar — Size - размер всего создаваемого приложения; Q MIDlet -Jar - URL - местонахождение проекта; Q MIDlet - Name - имя проекта; Q MIDlet - Vendor - создатель программы; Q MIDlet - Version - версия программы; ,Q MicroEdition - Configuration - конфигурация; Q MicroEdition - Profile - выбранный профиль. Вся заданная информация для мидлета будет находиться в JAD файле. По ходу работы над проектом имеется возможность изменения заданных атрибутов с помощью кнопки Settings на панели инструментов рабочего окна J2ME Wireless Toolkit 2.1. Подробно о файлах JAD и JAR будет рассказано в конце этой главы в разделе 3.4. Все оставшиеся вкладки, имеют различные дополнительные свойства и заданные на этих вкладках значения почти всегда можно оставлять по умолчанию. Нажав на кнопку ОК после всех установок, в окне Settings for project «Demo>> будет создан новый проект Demo.
Средства разработки мобильных приложений
Optional 8 User Defined ! MIDIets ,j Push Registry j| Permissions
Рис. 3.27. Вклакда Required Среда программирования J2ME Wireless Toolkit 2.1, к сожалению, не имеет своего текстового редактора. Для создания исходного кода приложения вам необходимо написать код программы в любом удобном текстовом редакторе и поместить этот код в директории J2ME Wireless Toolkit 2.1. Как это делается? В тот момент, когда вы нажмете на кнопку ОК, в окне Settings for project «Demo» будет создан новый проект, в нашем случае это Demo. А в консоли главного окна среды программирования J2ME Wireless Toolkit 2.1 появятся примерно следующие строки: Creating project "Demo" Place Java source f i l e s in " C : \ W T K 2 l ^ a p p s \ D e m o \ s r c " Place application resource f i l e s in "C:\WTK21\apps\Demo\res" Place application library f i l e s in "C:\WTK21\apps\Demo\lib"
Из этих строк следует, что файлы исходного кода (это, как правило, файлы с расширением *.java), необходимо поместить в директорию C:\WTK21\apps\Demo\src. Файлы ресурсов, иконки, изображения и так далее помещаются в директорию
J2ME Wireless Toolkit 2.1 C:\WTK21\apps\Demo\res; и файлы библиотек, если таковые используются в C:\WTK21\apps\Demo\lib. То есть, создав исходный код приложения в текстовом редакторе, просто сохраните код в директорию: C:\WTK21\apps\Demo\src. Кроме трех перечисленных папок, созданных в рабочем .каталоге проекта Demo, будут автоматически сгенерированно еще четыре папки: Q bin - содержит файлы: jar, jad и файл манифеста. Более подробно об этих файлах рассказывается в разделе 3.4, где будет рассматриваться упаковка программ; Q classes - хранит проверенные откомпилированные классы; О tmpclasses - хранит непроверенные откомпилированные классы; Q tmplib - временная папка для хранения фалов.
3.3.3. Компиляция и запуск программы в J2ME Wireless Toolkit 2.1 В качестве демонстрационного примера мы используем проект Demo, созданный автоматически SUN ONE Studio 4 Mobile Edition в разделе 3.2.3. Найдите исходный код:Не!1оМШ1е1 проекта Demo в директории, которую вы задали для размещения программ в SUN ONE Studio 4 Mobile Edition или возьмите код HelloMIDlet с компакт диска в папке \Code\ HelloMIDlet, поместите его в директорию C:\WTK21\apps\Demo\src. Затем нажмите кнопку Build на панели инструментов для компиляции и компоновки всего проекта. В рабочее окно J2ME Wireless Toolkit 2.1, добавятся две строчки: / Building "Demo" Build complete Здесь я, конечно, исключаю возможность появления ошибок при компиляции, но в реальном программировании приложений без этого не обойтись, программист где-нибудь да забудет поставить точку с запятой. После компиляции и компоновки проекта, нажмите кнопку Run, и на экране появится эмулятор по умолчанию DefaultColorPhone, предоставляемый J2ME Wireless Toolkit 2.1 и изображенный на рис. 3.28. На экран эмулятора будет выведено имя проекта, нажав на клавишу эмулятора Select или Launch, вы попадете в рабочий цикл программы, и на экране эмулятора появится надпись Test string. Нажав на клавишу Exit можно выйти из приложения. По окончанию работы эмулятора, в консоли рабочего окна J2ME Wireless Toolkit 2.1, появятся примерно следующие надписи: Running with storage root DefaultColorPhone Execution completed. Рис. 3.28. Эмулятор телефона DefaultColorPhone
ВЯВШ! i Средства разработки мобильных приложений 4 9 3 0 8 4 bytecodes executed 57 thread switches 487 classes in the system (including system c l a s s e s ) 2 8 4 4 dynamic o b j e c t s allocated ( 9 2 0 6 8 'bytes) 2 garbage collections ( 6 1 9 7 6 bytes collected) Это строки информационного характера, которые знакомят вас с произошедшими процессами в момент работы приложения. Для того чтобы протестировать созданную программу на других телефонных эмуляторах, необходимо в поле Device среды разработки приложений J2ME Wireless Toolkit 2.1, выбрать из списка'нужный эмулятор. В составе J2ME Wireless Toolkit 2.1 имеются следующие эмуляторы телефонов: Q DefaultColorPhone — "простой телефон с цветным дисплеем; Q DefaultGrayPhone - телефон с монохромным дисплеем; р MinimumPhone - телефон с минимальными техническими характеристиками; Q MediaControlSkin — простейший эмулятор телефона контролирующий воспроизведение звуков; Q QwertyDevice - портативное устройство с клавиатурой. Также существует возможность интеграции телефонных эмуляторов, сторонних производителей, о чем будет рассказано в следующей главе.
3.4. Упаковка программ - При создании проекта и последующей компиляции исходного кода, у вас появятся два файла: JAD-файл и файл манифеста. Если вы работаете с Sun ONE Studio; то оба файла будут, находиться в рабочем каталоге проекта. Если вы используете среду программирования J2ME Wireless Toolkit, то JAD-файл и файл манифеста будут помещены в папку \bin рабочего каталога приложения. Давайте отталкиваться от созданного в разделах 3.2,3 и 3.3.2 проекта Demo, и мидлета HelloMIDlet. В этом случае в соответствующих директориях двух средах программирования будут находиться два файла: Demo.jad и MANIFEST.MF.
3.4.1. Файл манифеста Файл манифеста MANIFEST.MF описывает возможные атрибуты создаваемого приложения. Откройте файл манифеста программы HelloMIDlet с помощью любого текстового редактора, например блокнота и вы увидите следующие строки: MIDlet-1: Demo, Demo.png, HelloMIDlet MIDlet-Name: Demo MIDlet-Vendor: Unknown MIDlet-Version: 1.0 MicroEditicri-Conf i g u r a t i o n : CLDC-1. 0 M i C r o E d i t i o n - P r o f i l e : MIDP-1.0
•
Упаковка программ Эти строки описывают атрибуты приложения. При создании проекта с J2ME Wireless Toolkit в разделе 3.3.2 этой главы упоминалось о диалоговом окне Settings for project «Demo» изображенном на рис. 3.26, Это окно разделено на семь вкладок, в каждой из которых указываются различные атрибуты создаваемого приложения. На основе заданных атрибутов в диалоговом окне Settings for project «Demo», и происходит генерация файла манифеста, а так же^В-файла.
3.4.2. Файл JAD Как уже упоминалось, в рабочем каталоге проекта «Demo» будет находиться еще один файл Demo.jad. JAD-файл в мобильных приложениях еще называют ava дескриптором приложения G Application Descriptor). Этот файл используется телефоном во время работы программы для получения информации об имеющихся классах, изображениях, пиктограммах и звуковых файлах всей программы. На основе полученной информации происходит управление внутренними ресурсами приложения. Если вы переместитесь в рабочий каталог проекта «Demo» и найдете сгенерированный файл Demo.jad, то увидите иконку в виде телефона с левой стороны от названия файла. Сделав двойной щелчок левой кнопкой мыши на файле Demo.jad, вы запустите эмулятор телефона вне зависимости от того, открыта ли в данный момент одна из сред программирования или нет. Это еще раз указывает на то, что JAD-файл используется для управления работой программы. Но есть и еще одна интересная особенность JAD-файла. Откройте файл Demo.jad с помощью любого текстового редактора и вы увидите следующие строки: MIDlet-1: Demo, Demo.png, HelloMIDlet MIDlet-Jar-Size: 30 MI.Dlet-Jar-URL: Demo, jar MIDlet-Name: Demo MIDlet-Vendor: Unknown MID.let-Version: 1.0 MicroEdition-Configuration: CLDC-1.0 MicroEdition-Profile: MIDP-1.0 JAD-файл тоже содержит описание атрибутов приложения и они во многом дублируются в файле манифеста MANIFEST.MF. В программах Java 2 ME, JADфайл - это дескриптор приложения и используется для управления работой программы. Сервис телефона перед запуском программы обращается именно к JADфайлу, определяя тем самым возможность работы всей программы на этом телефоне. Если один из параметров будет не допустимым для этой модели телефона, то приложение не будет запущено. Например, телефон не поддерживает ту . или иную версию конфигурации и профиля, или размер JAR-файл, больше допустимой памяти » телефоне выделенной для Java программ (правда в этом случае вы вообще не сможете загрузить приложение в телефон).
Средства разработки мобильных приложений 3.4.3. Файл JAR В языке Java существует возможность архивации файлов приложения в один файл с расширением *.jar. Файл JAR - это архив, содержащий сопутствующие классы и графические изображения всего приложения. JAR-архив основан на обыкновенном zip-фррмате, использующемся повсеместно. При написании п'роrpaMto на Java под различные компьютерные операционные системы, программист волен сам выбирать, будет ли он распространять свое приложение в заархивированном виде или в оригинальном. Ситуация с распространением-переносом программ под мобильные телефоны радикально противоположная. Телефоны ограничены в своих ресурсах и в среднем память, отведенная под Java программу, колеблется от 30 до 80 килобайт. Эти цифры обязательно надо учитывать при создании мобильных приложений. Размер в 40-50 килобайт считается оптимальным. В связи с этим все мобильные программы обязаны распространяться в заархивированном виде, то есть в JAR-файле. Написав программу для телефона необходимо ее упаковать в jar-архив. Вернемся к примеру HelloMIDlet проекта Demo и рассмотрим на практике создание JAR-файла. При использовании Sun ONE Studio 4 Mobile Edition создание JAR-файла происходит автоматически после компиляции и компоновки всего проекта и созданный архив помещается в рабочий каталог. В среде J2ME Wireless Toolkit 2.1 после компиляции исходного кода необходимо произвести явную упаковку программы. Выберете в меню среды J2ME Wireless Toolkit опцию Project => Package => Create Package. На несколько секунд в рабочем окне появится небольшое диалоговое окно, показывающее процесс упаковки программы в JAR-файл. После чего в каталоге проекта Demo в папке \Ып появится файл Demo.jar. А теперь перейдите в рабочий каталог проекта Demo и найдите сформированный архив Demo.jar. Затем воспользуйтесь любым архиватором, поддерживающим zip-формат, например WinRar или WinZip и откройте файл Demo.jar. Вы увидите файл HelloMIDlet.class и папку META-INF, открыв которую обнаружите файл манифеста MANIFEST.MF. Что происходит при создании архива? В момент упаковки приложения в JAR-файл, происходит копирование всех имеющихся откомпилированных и проверенных классов и графических изображений (если таковые имеются) и размещение их в JAR-файл, то есть происходит архивация всей программы. В рассмат-. риваемом примере HelloMIDlet существует всего один класс, но если программа имеет большое количество классов, то все они помещаются в JAR-файл. Также происходит копирование файла манифеста MANIFEST.MF в папку META-INF. После упаковки в рабочем каталоге приложения будут находиться два файла с расширением JAR и JAD и именно в таком виде можно перенести программу в мобильный телефон посредством Интернета или компьютера связанного с мобильным телефоном любым из способов. Все приложения и игры, написанные на Java 2 ME, распространяются именно таким образом. Файл с расширением JAR содержит упакованную программу, а файл с расширением JAD описывает содержимое JAR-файла. При загрузке программ в телефон необходимо указывать путь
Упаковка программ
lllllHHH
к JAD файлу, то есть дескриптору приложения и на основании атрибутов JADфайла происходит работа Java программы. Единственное исключение - это телефоны марки Siemens. При загрузке программ в телефон этой марки нужно указывать путь к J АН-файлу, о чем подробно будет рассказано в следующей главе, в-которой будет рассматриваться программное обеспечение, поставляемое производителями мобильных телефонов для эмуляции работы мобильных телефонов различных моделей.
Глава 4. Телефонные эмуляторы Интегрированные средства разработки приложений для мобильных телефонов рассмотренные в предыдущей главе имеют в своем составе несколько эмуляторов мобильных устройств несуществующих марок телефонов. Эмулятор телефона это приложение, программно эмулирующее работу реального телефона, учитывая все технические характеристики этого устройства. Большинство производителей мобильных телефонов имеют в своем арсенале наборы инструментальных средств для программирования телефонов называемых SDK (Software Developer Kit) и множество встраиваемых модулей для эмуляции определенных моделей. Самое большое количество программного обеспечения предоставляется компанией Nokia. Сайт этой компании просто «ломится» от изобилия всевозможных программ. Линейка разнообразных моделей телефонов, выпускаемых одним производителем, обычно делится по ценовым категориям. Чем дороже модель - тем больше функциональных возможностей включено в это устройство, а значит, предусмотрена более мощная архитектура телефона. Как правило, все различия сводятся к нескольким параметрам: Q наличие или отсутствие операционной системы в телефоне; Q возможность работы с приложениями написанными на Java 2 ME и C++; Q количество памяти; Q разрешение дисплея телефона. В связи с этим очень полезно иметь как можно больше программных средств, эмулирующих реальные мобильные устройства, для того чтобы можно было протестировать создаваемую программу. Если вы программируете приложение на Java 2 ME, используя профиль MIDP 2.0 или MIDP 1.0, то на всех имеющихся моделях телефонов, где предусмотрена поддержка Java с соответствующим профилем, ваше приложение будет работать. Но, к сожалению, могут возникнуть проблемы в графическом отображении элементов пользовательского интерфейса, вследствие того, что присутствует ряд очевидных различий в визуальном представлении этих элементов. Также каждый из производителей телефонов придерживается своей системы навигации, что, безусловно, усложняет разработку программного обеспечения. Поэтому имеющиеся наборы SDK и эмуляторов отдельно взятых моделей телефонов, намного облегчают работу программиста. В своем большинстве программное обеспечение различных производителей интегрируется в визуальные среды от компании Sun Microsystems и Borland, либо существуют в виде отдельных программ. Со следующей главы мы начнем подробное изучение специфики создания приложений с помощью классов имеющихся в составе Java 2 ME.
1
Программное обеспечение телефонов Nokia К сожалению, в контексте этой книги невозможно рассмотреть все нюансы, возникающие при использовании различных телефонных эмуляторов. Количество различных моделей поддерживающих технологию Java 2 ME сейчас велико и переключаться от модели к модели будет сложно. Вследствие этого, за основу всех рассматриваемых программ в книге, взят нейтральный эмулятор телефона DefaultColorPhone (простой телефон с цветным дисплеем) из состава инструментариев корпорации Sun, рассмотренных в главе 3. Но, безусловно, очень часто ваше внимание будет акцентироваться и на различных проблемах возникающих при реализации тех или иных программ. Вам же необходимо самим отслеживать имеющиеся различия в рассматриваемых примерах. Эта глава поможет разобраться в тонкостях установки, настройки и работы с программным обеспечением от различных производителей. Компакт-диск, прилагающийся к книге, содержит замечательную коллекцию разнообразного программного обеспечения, необходимого в программировании мобильных устройств. Все программное обеспечение на диске разбито на.соответствующие папки по производителям. Представлены такие компании как Nokia, Siemens, Sony Ericsson, Motorola и Samsung. Подробная структура компактдиска рассмотрена в конце книги в Приложении 3. Все имеющиеся программы взяты непосредственно с сайтов вышеперечисленных компаний и распространяются абсолютно бесплатно, но требуют обязательной регистрации, без которой некоторые продукты вам установить не удастся.
4.1. Программное обеспечение телефонов Nokia Компания Nokia имеет, пожалуй, самое впечатляющее количество программного обеспечения. Многие программы даже не поместились на компакт-диск! Если вы не нашли на диске необходимые вам средства программирования, то посетите сайт компании Nokia: http: //forum.nokia.com. Все программное обеспечение, находящееся на компакт-диске или на сайте компании Nokia доступно бесплатно, но на основе регистрации, без которой вы не сможете установить ни один программный продукт этой компании. Поэтому первым делом необходимо посетить сайт этой компании, где, перейдя по ссылке Registration, вам будет предоставлена регистрационная форма, изображенная на рис. 4.1. Заполняя поля регистрационной формы, запомните обязательно свой пароль и «логин» для возможности дальнейшего доступа в систему. И главное, укажите свой адрес электронной почты, на который вам будут высылаться серийные номера отдельных продуктов. Такие серийные номера даются бесплатно, но только для зарегистрированных пользователей. Весь процесс регистрации происходит в несколько этапов. После того как вы заполните регистрационную форму, изображенную на рис. 4.1, на ваш e-mail придет письмо. Текст письма будет, естественно, на английском языке, в нем вам предложат подтвердить свои намерения в регистрации, для чего необходимо будет перейти по ссылке, имеющейся в этом письме. Перейдя по ссылке, вы попаде-
Телефонные эмуляторы Developer Home: Registration: Registration CONNECTING PEOPLE
to Forum Nokia
Forum Nokia is a vital resource to the mobile development community, with a current membership of more than one million developers who count on the site to keep updated on the latest tools, tips, insights, and Industry trends.
1
• All ll.ld.
jSearch Forum Nokia Help Advanced
I
(Vearoh)
m Newsletters Developer Platforms
Registration is free and protected by our strict privacy policy. User Name and Password
FORUM NOKIA
Series 40 Series 30
User name:' For CDMA Market
Password (mm e chjrjcten? •
Forum Nokia PRO
Confirm password; *
j
Resources Books
E-mal address: * О Yes. pit»* contact me via «-mail r«gjldin0 Forum Nokia updates I Next I
[ Cancel I
Device Specifications Porting Device Optimization
Рис. 4.1. Регистрационная форма те на страницу, регистрирующую вас и отсылающую вам еще одно послание. Это письмо будет содержать еще одну ссылку, по которой также надо будет перейти, уже для конечной регистрации в системе. Дальше на ваш домашний адрес, будет выслана бандероль с последней моделью телефона Nokia N-Gage QD (шутка). После двух писем и подтверждений регистрации вы станете зарегистрированным пользователем, и вам будут доступны любые ресурсы q сайта компании Nokia. Получив доступ в систему, вы сможете заказать необходимый серийный номер, который будет выслан на ваш e-inail, указанный при регистрации. Процесс получения серийного номера очень прост. Зайдя на сайт компании Nokia: http:// forum.nokia.com, с правой стороны Интернет страницы вы найдете ряд ссылок. Ссылка Tools&SDK приведет на страницу, отображающую все доступные на этот момент программные средства. Выбрав необходимый вам программный продукт, например Nokia Developer's Suite 2.0 for J2ME, вы попадете на страницу изображенную, на рис. 4.2. На этой странице вы можете, как скачать этот продукт (в том случае если вы1 утеряли, подарили или продали компакт диск к книге), так и заказать серийный номер. Под большой, красочно оформленной ссылкой Download now, имеется ссылка Serial number for this product, перейдя по которой вы сможете заказать серийный номер к этому продукту. Заказ серийных номеров других программ происходит таким же образом. Ниже перечислены названия всех имеющихся программных средств компании Nokia находящихся на компакт диске в папке \Nokia:
Программное обеспечение телефонов Nokia Щ|Ц FORUM
Developer Home: Resources: Tools & SDKs: Tools Detail ~
NOKIA
Nokia Developer's Sidle 2.0 for J2ME The NoKia Developer's Suite for the Java™ 2 Platform. Micro Edition. Version 2.0 for Windows provides developers with class libraries, APIs, and Nokia device emulators used to create mobile Java™ applications targeted to Mobile Information Device Profile (MIOP) 1.0 and MIDP 2.0. The tool can also be integrated with major Java application-specific IDE tools such as Borland JBullder and Sun ONE Mobile Edition. Developers can create MiDlets based on the MIDP 1.0 specification that will successfully Implement on Series 30, Series 40, and Series 60 NoMa devices, Including the Nokia 631 Ol, Nokia 351 Ol, NoMa 7210. and NoMa 3650 mobile phones. Use the Series 60 MIDP Concept SDK Beta 0.3, NoMa edition to develop MIDIets which are based on the MIDP 2.0 specification.
Developer Platform
idded:
Developer Platform
Developer Platform
OS.Jun-03
} Requirements: : • Window* 2000 SP2. Windows XP SP1. or Red i Hat 7.2 | •Jjirj'" Runtime Environment(JRE)1.4.1_02 i Ol Itttr
i •2WUBofRAU
Звпез 40 Series 60 Series 80
i -100 MS ottieedwsp.ee
i -300 MHz or fjster Pentium-elm processor i (350 MHz recommended) i -84.000 colors with 1024x768 resolution i • Keyboard jnd mouse
For CDMA Market orum Nokia PRO
: Download version for
Key features: Full development cycle when Integrated into Borland JBuilder and Sun ONE Mobile Edition • Also works In stand-alone mode with additional external tools • Support for MIDP 1.0 and MIDP 2.0 • Provides the Series 60 MIDP Concept SDK Beta 0.3, NoMa edition • Deploys on devices using IrDA, USB, and RS232 (available on Windows platforms) • Provides an FTP-upload capability, Including WML deck file generation • Supports application signing with public/private key model • Integrated Audio converter for MIDI and ring tone XML files • Support for Series 30, Series 40, and Series 60 devices • IDEs supported: Borland JBullder 8 '
||v*ldows(39M8)
В
\ [О Downtoadnowj
Device Specifications
I You can i«qu«sti«rijl number «Is» during the | irwtjlletion, procta.
ppjljpg
Suit* foi J2ME*4, , 1 » Suit» fot J2y E . ImUlltttoB Outdt
Device Optimization Technologies Communities
! User Ould«Xs):
Discussion Boards Professional Support it j friend jbout this tool »
Testing
Рис.4.2. Окно заказа серийного номера Q Nokia Developer's Suite 2.0 for J2ME; * Q Series 40 Developer Platform 2.0 SDK; Q Series 60 MIDP 2.1 SDK; Q Series 90 MIDP 1.0 SDK; Q Nokia 5100 SDK 1.0; Q Nokia 3410 SDK 1.0; a Nokia PC Suite 5.1. Программная архитектура всех телефонов Nokia делится на серии платформ (Series Developer Platform): серии 40,60,80 и 90. Раньше еще существовала платформа тридцатой серии, но сейчас она объединена в сороковую серию. Запомнить какие из моделей телефонов принадлежат соответствующим сериям тяжело, но очень легко различать модели по сериям с помощью разрешения дисплея, разбив их на четыре категории: Q серия 40 - телефоны, входящие в эту серию имеют разрешение дисплея 96x65, 128x128 и 128x160 пикселей;
*,.'•:
Телефонные эмуляторы
Q серия 60 - разрешение дисплея 176x208 пикселей; Q серия 80 - разрешение дисплея 640x200 пикселей; О серия 90 - разрешение дисплея 640x320 пикселей. Телефоны, принадлежащие к серии 40, не имеют полноценной операционной системы и работают на основе прошивки. Для этой серии телефонов доступно программирование приложений только на языке Java 2 ME, при условии поддержки самой технологии Java конкретной моделью телефона. Серии 60, 80 и 90 построены на операционной системе Symbian и кроме возможности программирования на языке Java, дают возможность в создании приложений на языке C++. Издательство ДМК Пресс готовит к выходу книгу по программированию мобильных телефонов на базе операционной системы Symbian. Так как модели телефонов разделены на серии, в свою очередь все имеющиеся программные средства так же подразделены соответствующим образом. Существует большое количество SDK для всех четырех серий телефонов, а также множество отдельно настраиваемых' модулей эмулирующих конкретные модели телефонов. Прежде чем устанавливать эмуляторы телефонов Nokia, необходимо установить основной пакет Nokia Developer's Suite 2.0 for J2ME. Все телефонные эмуляторы встраиваются в этот пакет.
4.1.1. Инструментарий Nokia Developer's Suite 2.0 for J2ME Перед тем как вы начнете устанавливать пакет Nokia Developer's Suite 2.0 for J2ME, позаботьтесь о получении серийного номера для этого продукта с сайта компании Nokia: http: //forum.nokia.com. На компакт-диске в папке \Nokia, находится файл nds_jme_v_2_0.zip. Распакуйте этот архив в любую удобную директорию. После распаковки архива найдите файл setup.exe и нажмите на нем два раза левой кнопкой мыши, вызвав тем самым программу установки пакета. В первом появившемся окне Welcome программы установки пакета изображенном на рис. 4.3, от вас потребуют ввода серийного номера. Окно Welcome программы установки содержит два поля: Forum Nokia Username - для ввода «логина» под которым вы зарегистрированы на сайте компании Nokia и поле Product Serial Number где необходимо ввести серийный номер полученный по электронной почте. Если вы еще не заказывали серийный номер для устанавливаемого пакета, но являетесь зарегистрированным пользователем, то можно указать только свой логин в поле Forum Nokia Username и нажать на кнопку Next. После чего произойдет соединение с сайтом forum.nokia.com, где вы сможете заказать серийный номер. После ввода серийного номера и логина, нажмите кнопку Next для перехода в окно Choose install set, изображенное на рис. 4.4. Окно программы установки Choose install set имеет три варианта выбора для последующей установки пакета Nokia Developer's Suite 2.0 for J2ME: О Standard installation. Производит стандартную установку в виде отдельно существующего пакета без интеграции в какую-либо среду программирования;
Программное обеспечение телефонов Nokia Nokia Developer's Suite 2.0 for JZME(TM)
You have selected a Nokia developer product to be installed. You have the following installation options: - If you are already a member of Forum Nokia and you have a serial number for this product, please fill in the text fields below and then press the "Next'button - If you are not a member of Forum Nokia or do not have a serial number for this product, please leave the text fields below empty and then press the "Next" button
Forum Nokia Username: Product Serial Number: [ InstallAnywhere by Zero 0 Cancel
Рис. 4.З. Окно Welcome программы установки пакета Nokia Developer's Suite 2.0 for J2ME
Standalone installation Choosing this option will install Nokia Developer's Suite as л standalone product.
Integration with Borland JBuilder Choosing this option will install Nokia Developer's Suite integrated with Borland JBuilder IDE.
Integration with Sun(TM) ONE Studio Choosing this option will install Nokia Developer's Suite integrated with Sun Forte(TM) for Java(TM) IDE or Sun ONE Studio. Mobile Edition.
Рис. 4.4. Окно Choose install set программы установки пакета Nokia Developer's Suite 2.0 for J2ME
Телефонные эмуляторы О Integration with Borland JBuilder. Интегрирует пакет Nokia Developer's -* Suite 2.0 for J2ME в интегрированную среду программирования Borland JBuilder; Q Integration with Sun™ ONE Studio. Происходит интеграция с визуальной средой программирования Sun ONE Studio. Выберите необходимый вариант установки или комбинацию вариантов, нажав на кнопку возле выбранной надписи, и перейдите в следующее окно после нажатия кнопки Next. Рекомендую выбрать Standard installation и интеграцию в установленную на вашем компьютере среду программирования. В предыдущей главе были рассмотрены средства программирования от компании Sun Microsystems, поэтому в дальнейшем при установке пакетов всех имеющихся производителей мы будем придерживаться программных средств компании Sun Microsystems. После того, как вы нажмете кнопку Next в окне Choose install set, вы попадете в окно Select the installation directory of your Sun IDE, показанное на рис. 4.5.
Please select the Installation directory of your Sun ONE Studio or Sun Forte for Java. The installer will automatically extend the Installation directory with the required directories.
Please choose a directory: C: Program Files\s1 studio Vne •Restore Defaut Directory
by Zero 0
Рис. 4.5. Окно Select the installation directory of your Sun IDE Убедитесь, что в поле Please choose a directory прописан правильный путь в директорию с инструментарием Sun ONE Studio 4 Mobile Edition и нажмите кнопку Next. Дождитесь конца инсталляции, и не забудьте после всех действий перезагрузить компьютер. После удачной установки запустите программу из меню ПУСК => Все программы => Nokia Developer Tools => Nokia Developer's Suite2.0 for J2ME =» Run
Программное обеспечение телефонов Nokia | as a Standalone и вам откроется основное окно программы, Nokia Developer's Suite2.0 for J2ME, изображенное на рис. 4.6. f... Nokia Developer's Suite for J2ME(TM) Emulators
Tools
Help
•Pi
Noki
uilfbihrtft» lava™? Pljri"fr\nri Mi*>*n Е
Create Class
Create Application - Package
Sign Application Package
Deployment
Start Emulators
Messages:
Gear Messages
Audio Converter
NOKIA
Рис. 4.6. Окно Nokia Developer's Suite for the Java™ 2 Platform, Micro Edition . С левой стороны основного окна программы имеется вкладка расположенная вертикально вдоль всего экрана дисплея. Эта вкладка состоит из шести больших интерактивных кнопок: Р Create Class - создание класса; Q Create Application Package - создание пакета; О Sign Application Package - проверка сигнатуры приложения; Q Deployment - показывает подключенный к компьютеру телефон и предоставляет связь с сервером;
•
Телефонные эмуляторы **.-*4i •"*
О Start Emulators - запуск эмуляторов; . Q Audio Converter - аудио-конвертер для конвертации звуковых файлов. Нажав на кнопку Start Emulators, вам откроется окно, изображенное на рис. 4.7. £• NoMa Developer's Suite for JZME(TM) File
Emulators
Tods
;
Q©®
Help
вчамвииигаяг"
Nokia Developer's Suite,fcrth«;Java'"2 Platform, Micro Edition
i Application: C: WTK21 tepps»DemoWn\Demo.jad
I
-.
j
Configure...
« •
Create Class
Select Emutetors: 0 Nokia 721 0 МЮР SDK И .0 <default> 0 Series 60 MDP Concept SDK Beta 0.3.1 , Nokia editor*
Create Application Package
Emulate
•
Sign Application Package
I
Deployment
Start Emulators
ь
Messages:
Clear Messages
Audio Converter
NOKIA
General )
Рис. 4.7. Окно выбора телефонных эмуляторов В состав пакета Nokia Developer's Suite2.0, входит два эмулятора - это эмулятор телефона Nokia 7210 сороковой серии и эмулятор телефонов шестидесятой серии, который представляет некий собирательный образ телефонов этой серии. Для того чтобы запустить на эмуляторах, приложение, необходимо в поле Application, указать путь до JAR-файла, а в поле Select Emulators, выбрать телефонный эмулятор с помощью галочки с левой стороны названия эмулятора. Здесь нет ограничений и можно выбрать сразу оба эмулятора. После чего нажмите на кнопку Emulate, и на экране появится выбранный эмулятор телефона. На рис. 4.8
Программное обеспечение телефонов Nokia Рис 4.8. Телефонный эмулятор Nokia 7210
показан эмулятор Nokia 7210 сороковой серии показывающий работу проекта Demo, созданного в главе 3 и выводящего на экран строку текста Test string. В окне Nokia Developer's Suite for the Java™ 2 Platform, Micro Edition, где перечислены доступные эмуляторы, с правой стороны имеется кнопка Configure, нажав на эту кнопку, вы попадете в окно, в котором можно задать ряд установок, осуществляющих конфигурацию доступных на данный момент эмуляторов. В частности в поле Select language, можно выбрать язык для меню телефона, а в поле Emulators, добавить или удалить эмуляторы телефонов с -помощью кнопок Add (добавить) и Remove (удалить). Если при инсталляции пакета Nokia Developer's Suite2.0 вы указали интеграцию с визуальной средой программирования Sun ONE Studio в окне Choose install показанное на рис 4.4, то при работе с Sun ONE Studio 4 Mobile Edition, вы сможете запускать соответствующие эмуляторы. Для этого необходимо в Sun ONE Studio 4 Mobile Edition выбрать .команду в меню Tools => Nokia =» Developer's Suite for J2ME => Start Emulators, после чего появится диалоговое окно Start Emulators. В этом окне нужно указать путь к приложению в поле Application и в поле Select Emulators выбрать необходимый эмулятор телефона Nokia. Пакета Nokia Developer's Suite2.0 представляет собой некую базу, в которую в последствии встраивается основная часть имеющихся телефонных эмуляторов и SDK компании Nokia. Проинсталлируйте все имеющиеся SDK находящиеся на компакт-диске в папке \Nokia самостоятельно, теперь этот процесс не должен вызвать никаких трудностей. Также на компакт-диске в папке \Nokia\Linux находится пакет Nokia Developer's Suite под операционную систему Linux и телефонный эмулятор тридцатой серии.
4.1.2. Программа Nokia PC Suite 5.1 В качестве приятного бонуса в папке \Nokia на компакт-диске к книге вы сможете также обнаружить бесплатно распространяемую программу Nokia PC Suite 5.1, обеспечидающую связь телефона с компьютером и содержащую в своем составе большое количество разнообразных утилит. Q Nokia Application Installer - помогает устанавливать Java 2ME приложения на телефоны Nokia; Q Nokia Content Copier - производит резервное копирования информации с телефона на компьютер и удаляет файлы с телефона; О Nokia Image Converter - преобразует изображения в форматах *.bmp, *.gif, *.ipg, *.ipeg, *.png, *.otb, *.wbmp, в фоновое изображение для телефона Nokia;
Телефонные эмуляторы Q Nokia PC Sync - синхронизирует телефон с компьютером; Q Nokia PC WAP Manager - изменяет установленные WAP настройки телефона через компьютер; Q Nokia Phone Browser - осуществляет управление папками телефона через проводник операционной системы Windows; О Nokia Phone Editor - производит управление различными функциями телефона через компьютер; Q Nokia Sound Converter - конвертирует файлы MIDI для последующего воспроизведения их на телефоне. Программа Nokia PC Suite 5.1 русифицирована и вы всегда сможете обратиться к контекстной справке, если возникнут осложнения с использованием одной из утилит.
4.7.5. Дополнительные пакеты Nokia В профиле MIDP 1.0 не доступна работа со звуком и рядом других возможностей, поэтому каждый из производителей телефонов поставляет свои пакеты с дополнительными классами. Для телефонов Nokia доступно два дополнительных пакета. Q com. nokia. mid. sound - содержит класс и интерфейс обеспечивающие работу со звуком. Q SounListener - этот интерфейс используется для получения событий связанных с воспроизведением; Q Sound - обеспечивает работу со звуком. Q com. nokia. mid. ui - графические расширения для классов Java 2 ME; Q DirectGraphics - интерфейс расширяющий графические классы; Q DeviceControl - имеет методы контролирующие ряд функций телефона; Q DirectUtils - содержит дополнительные утилиты; Q Full Canvas - обеспечивает работу в полноэкранном режиме. По мере прочтения этой книги вам станет понятно назначение перечисленных классов.
4.2. Программное обеспечение телефонов Siemens Компания Siemens тоже имеет «е малое количество моделей телефонов, которые поддерживают технологию Java 2 ME. Все средства программирования распространяются бесплатно, но требуют предварительной регистрации на сайте компании Siemens www.siemens-mobile.com/developer. На компакт-диске к книге в папке \Siemens, вы найдете следующие программы: Q Siemens Mobility Toolkit for Java Development; Q SMTK Emulator Pack for MC60; a SMTK Emulator Pack for C60; Q SMTK Emulator Pack for M55;
Программное обеспечение телефонов Siemens а SMTK Emulator Pack for M50; О SMTK Emulator Pack for S57; , Q SMTK Emulator Pack for S55; . a SMTK Emulator Pack for SL55; a SMTK Emulator Pack for SL45; О SMTK Emulator Pack for C55; , О SMTK Emulator Pack for 2128; О Siemens Date Suite. В качестве основного пакета выступает программа Siemens Mobility Toolkit for Java Development, в которую происходит интеграция имеющихся телефонных эмуляторов различных моделей.
4.2.1. Пакет Siemens Mobility Toolkit На компакт-диске в папке \Siemens находится файл smtk_0_13_2_59, нажав два раза левой кнопкой мыши на этом файле, вы запустите программу установки пакета Siemens Mobility Toolkit. Установка инструментария достаточно проста и вам необходимо в появляющихся окнах, лишь задавать нужные директории для установки пакета. Сам пакет не содержит телефонных эмуляторов, но является основным и первым пакетом, который необходимо установить на компьютер. Все последующие программные средства компания Siemens, а это телефонные эмуляторы и всевозможная документация, встраиваются в пакет Siemens Mobility Toolkit. На рис. 4.9 показаны все имеющиеся эмуляторы.
Рис 4.9. Эмуляторы телефонов Siemens
Эмуляторы, находящиеся на компакт-диске в папке \Siemens, устанавливаются автоматически встраиваясь в пакет Siemens Mobility Toolkit. После установки всех имеющихся программных средств, на рабочем столе компьютера должны появится два ярлыка: SMTK Emulator Launcher и SMTK Manager. Запустив утилиту SMTK Manager, вы увидите небольшое диалоговое окно, изображенное на рис. 4.9. Диалоговое окно SMTK Manager состоит из трех вкладок: О Select target emulator - позволяет выбрать эмулятор по умолчанию, который будет запускаться при каждом старте SMTK Emulator Launcher. Так-
Телефонные эмуляторы <& SMTK Manaaer Help Select target emulator | SMTK management | Integration with IDEs | Phone model Siemens 2128 Siemens C55 Siemens C60 (Chinese! <
:
Ai
Set target I
jsjj' >'
Device info
Г Use the current target emulator for MIDIet execution Quit
Рис. 4,10. Диалоговое окно SMTK Manager же имеется кнопка Device info для просмотра справочной информации по выбранному эмулятору; Q SMTK management - на этой вкладке при помощи кнопки Remove можно удалить выбранный из списка эмулятор; Q Integration with IDE's - производит интеграцию со средой программирования Borland JBulder с пятой по девятую версии. Установленные телефонные эмуляторы фирмы Siemens вы также можете подключить в среду программирования SUN ONE Studio 4 Mobile Edition. Для этого в среде программирования SUN ONE Studio 4 Mobile Edition выберете вкладку Выполнение в окне Explorer и перейдите по каталогам Device Emulator => Registry Installed Emulators", а в появившемся меню изберете команду Add emulators. В следующем диалоговом окне Select emulator installation directory укажите директорию, в которой установлены эмуляторы телефонов компании Siemens. Если вы установили программу Siemens Mobility Toolkit по умолчанию в корневой каталог то, например путь к телефонному эмулятору М55, будет таким: C:\siemens\SMTK\emulators\M55. Второй ярлык появившейся на рабочем столе запускает непосредственно программу SMTK Emulator Launcher. После запуска программы появится небольшое диалоговое окно, показанное на рис. 4.11. В диалоговом окне SMTK to Launcher, можно выбрать телефонный эмулятор необходимый вам для работы. После этого появится эмулятор телефона и окно команд (commands), изображенное на рис. 4.12. В окне Commands имеется ряд команд, нас интересует команда Start Java Application с поA* Emulator to Launch мощью которой можно запустить упакованную Select phone model Siemens 2128 л Java программу. После двойного щелчка на коSiemens C55 манде Start Java Application, появится диалогоSiemens CSO (Chinese) вое окно, в котором нужно указать путь к JAR Г™ Use the current target emulator Cancel
Рис. 4.11. Диалоговое окно SMTK to Launcher
Программное обеспечение телефонов Siemens Рис. 4.12. Окно Commands
файлу. Замете, что в телефонных эмуляторах Nokia указывался путь к JAD файлу, а в эмуляторах Siemens к JAR файлу. Выбрав JAR-файл нажмите на кнопку ОК и произойдет запуск выбранного приложения на эмуляторе.
4.2.2. Программа Siemens Date Suite
MSM: commands MM: No Service MM: Limited Service MM: Full Service Power: Begin Low Power Power: End Low Power SMS: Incoming Short Message SMS: Immediate Message SMS: Status Report SMS: Toggle Voice Message Switch Off Change microedition.locale Choose Network Filesystem
В папке \Siemens, на компакт-диске также можно найти программу Siemens Date Suite обеспечивающую связь телефона с компьютером, которая состоит из следующих утилит: Q Управление контактами - позволяет управлять контактами на карте SIM и телефонной памяти; Q Управление сообщениями SMS и EMS - осуществляет передачу сообщений SMS и EMS с компьютера; Q Редактор мелодий - создает новые мелодии или импортирует имеющиеся в телефон;' Q Редактор рисунков —, конвертирует изображения форматов: *.jpg, *.tif, *.gif, *.bmp, в фоновый рисунок для телефона; Q XTNDConnect PC — производит автоматическую синхронизацию с программами Outlook и Lotus Notes; Q Data Exchange Software - позволяет производить обмен данными между телефоном и компьютером; Q GPRS Modem Assistant - настраивает GPRS соединение, для работы с компьютера.
4.2.2. Дополнительные пакеты Siemens Компания Siemens имеет десять больших пакетов призванных расширить функциональность классов платформы Java 2ME. Существуют следующие пакеты: Q com. Siemens .mp - пакет расширения имеющий один класс. Q MIDlet - абстрактный класс идентичный классу MIDlet в Java 2 ME. О com.Siemens.mp.color_game - содержит классы для создания мобильных игр. Q GameCanvas - абстрактный класс, содержащий основные элементы игрового интерфейса; Q Layer - абстрактный класс, отвечающий за уровни представляемые в игре; Q LayerManager - менеджер уровней; Q Sprite - создает анимационные изображения;
' Q Q G Q О G Q Q Q Q Q Q О Q О О Q Q О О U U О Q Q О О Q О Q Q Q G Q
Телефонные эмуляторы
TiledLayer - отвечает за создание фоновых изображений в игре. com. Siemens . mp. game - имеет ряд игровых специфических классов; Extendedlmage - улучшает работу с изображениями; GraphicObj ect — суперкласс для классов Sprite и TiledBackground; GraphicObj ectManager - менеджер графических объектов; Light — класс работы со светом; Melody - воспроизводит мелодии; MelodyComposer - обеспечивает компрессию мелодии; Sound - работает с телефонными звуками; . Sprite - создает анимационные последовательности; TiledBackground - создает фоновые изображения; Vibrator - обеспечивает вибрацию телефона. com. Siemens .mp.gsm- снабжает дополнительными функциями связь GSM; Cal - класс, обеспечивающий вызов исходящих звонков на номер телефона; PhoneBook - класс, осуществляющий доступ к телефонной книге; SMS - класс, предоставляющий возможность посылки SMS сообщений. com. Siemens .mp. io — сетевой пакет. ConnectionListener - интерфейс, определяющий возможности в получении связи; Connection - поддерживает передачу данных через SMS и IrDA; File - обеспечивает доступ к файловой системе телефона. com. Siemens .mp. Icdui — улучшает функциональность'класса Image в Java 2 ME. Image - класс, позволяющий загружать дополнительные графические форматы. com. s iemens . mp. m5 5 - пакет для модели телефона Siemens m55 имеющий один класс. Ledcontrol — позволяет управлять дополнительными клавишами телефона; com. Siemens .mp.media — добавляет возможность работы с библиотекой Mobile Media API. Control - интерфейс, декларирующий контроль над объектами; , Controllable - интерфейс, обеспечивающий управление элементов; Player - интерфейс, регулирующий представления медиа-данных; PlayerListener - интерфейс, обеспечивающий получение асинхронных данных; TimeBase - интерфейс, реализующий таймер. com..Siemens .mp.media, control.— содержит два специфических интерфейса управления. ToneControl - реализует тональные звуки; VolumeControl — определяет громкость воспроизведения. com. Siemens .mp.ui - улучшает функциональность класса Image из пакета com ..Siemens .mp. Icdui.
Программное обеспечение Sony Ericsson Q Image - класс, улучшающий аналогичный класс Image «з пакета com. Siemens .mp. Icdui, содержит множество конструкторов и методов.
4.3. Программное обеспечение телефонов Sony Ericsson Множество телефонов компании Sony Ericsson поддерживают технологию Java 2 ME. Пакет инструментальных средств для программирования мобильных телефонов Sony Ericsson выполнен в виде одного файла и включает в себя все имеющиеся телефонные эмуляторы. Кроме того, после установки инструментария необходимо воспользоваться небольшим по размеру патчем. На компактдиске к книге в папке \Sony Ericsson находится следующие бесплатно распространяемые программы: Q Sony Ericsson J2ME SDK 2.1; О Sony Ericsson SDK 2.1 Patch; Q Sony Ericsson Communication Suit» Копания Sony Ericsson, по всей видимости, удачно сотрудничает с компанией Sun Microsystems. Весь пакет инструментальных средств Sony Ericsson J2ME SDK 2.1 основан на среде программирования J2ME Wireless Toolkit. Причем при инсталляции происходит установка сразу двух версий J2ME Wireless Toolkit. Первая версия J2ME Wireless Toolkit 1 предназначена для написания программ под профиль MIDP 1.0, а вторая версия J2ME Wireless Toolkit 2 для создания приложений под профиль MIDP 2.0. В итоге получается, что весь пакет инструментальных средств Sony Ericsson J2ME SDK 2.1 содержит полноценную среду программирования с набором телефонных эмуляторов. Работа в обеих средах программирования, 'идентична работе со средой J2ME Wireless Toolkit 2.1 рассмотренной в главе 3. Установка пакета Sony EricssonJ2ME SDK 2.1 происходит просто: вы должны указать необходимую директорию для инсталляции программы и лучше, если это будет корневой каталог, rie содержащий пробелов в названии папки. Единственный возникающий нюанс при инсталляции программы - это выбор устанавливаемых компонентов. На рис 4.13, изображено диалоговое окно Custom Setup. i В этом окне нужно выбрать среду J2ME Wireless Toolkit 1 или J2ME Wireless Toolkit 2, но если вы планируете писать программы под профиль MIDP 1.0 и MIDP 2.Q можно избрать обе среды программирования. Среда программирования J2ME Wireless Toolkit 1 имеет эмуляторы телефонов поддерживающих создание программ под профиль MIDP 1.0, и содержит следующие модели: Q P800; 4 Q T610; Q T616; Q Т630;
а Z600.
•
Телефонные эмуляторы Isr Sony Ericsson J2ME SDK 2.1.0_Beta - InstallShieJd Wizard Custom Setup Sebct the program features you want installed. Click on an icon in the list below to change how a feature is installed. Feature Description WTK1 supports P80Q, T628, T630, Z600, Z608 and T610 ! Series (T610, T618 and T616).
Documentation OnDeviceDebug PC Emulation WirelessToolKit.2.0 jgJrJ WTK2 MultiMedia support files
This feature requires 2SMB on your hard drive.
InstaP to: C:\SonyEricssonU2ME_SDK\PC_Emulatton\WTKH
Help
| [
Space
Change..,
l\text>
J[
Cancel
Рис 4.13. Окно Custom Setup Доступны и нейтральные телефонные эмуляторы, поставляемые вместе со средой программирования J2ME Wireless Toolkit: Q Default Color Phone - простой телефон с цветным дисплеем; Q Default Gray Phone - телефон с монохромным дисплеем; Q MinimumPhone - телефон с минимальными техническими характеристиками. В среде программирования J2ME Wireless Toolkit 2 доступно только три эмулятора - это: Q Z1010; а Z500;
а К7оо.
Все три эмулятора поддерживают профиль MIDP 2.0, как и сами телефоны этих трех марок компании Sony Ericsson. Если вы работаете в интегрированной среде программирования SUN ONE Studio 4 Mobile Edition, то можете подключить имеющиеся телефонные эмуляторы компании Sony Ericsson. В среде программирования SUN ONE Studio 4 Mobile Edition, выберите вкладку Выполнение в окне Explorer и нажмите на знак ключа с левой стороны каталога Device Emulator Registry. Раскроется ветка дерева этого каталога, выберите подкаталог Installed Emulators и в появившемся меню изберете команду Add emulators. Затем появится диалоговое окно Select emulator installation directory, где необходимо указать директорию, в которой установлены эмуляторы телефонов компании Sony Ericsson и нажать на кнопку Add. Если вы не изменяли директорию при инсталляции пакета Sony Ericsson J2ME SDK 2.1, то нужно выбрать следующий путь в диалоговом окне Select emulator installa-
Программное обеспечение телефонов Motorola tion directory для J2ME Wireless Toolkit 1: C:\SonyEricsson\J2ME_SDK\ PC_Emulation\WTKl. И путь для J2ME Wireless Toolkit 2: C:\SonyEricsson\ J2ME_SDK\PC_Emulation\WTK2. Затем выбираете необходимый эмулятор из списка и тестируете создаваемое приложение на телефонах Sony Ericsson. Также в папке \Sony Ericsson на компакт-диске находится программа Sony Ericsson Communication Suite осуществляющая связь телефонов Sony Ericsson с компьютером.
4.4. Программное обеспечение телефонов Motorola Программное обеспечение фирмы Motorola находится в папке \Motorola на компакт-диске и состоит всего из одной, но довольно функциональной программы. После ее установки на рабочем столе появится ярлык Motorola Lanchpad. Запустив программу Motorola Lanchpad, вы увидите диалоговое окно, показанное на рис. 4.14. Л Motorola Launchpad for J2ME Handset
IV600
Language
(ENGLISH
"Application
Select Handset... [ Advanced,..
:—: Explorer...
Class Name Run From JAD/JAR Execution Controls
j C:\WTK21\apps\Demo\bin\Demo.jad
Browse.,
•
Г* Keep Launchpad open after MIDIet launch' Г" Keep command window open after completion г Г~ Save command fine to batch fie -
Command Line C:\PROGRA~l\Motorola\SDKV4~l. 1FO\EMULAT~2. l\bin\eroulaYa.exe "C:\WTK21\apps\Demo\bin\Demo.jad" -deviceRle Resources\V600.props
Launch
Cancel
Рис. ~4,14. Программа Motorola Lanchpad for J2ME
В диалоговом окне Motorola Lanchpad for J2ME в поле Handset представлены все имеющиеся телефоны с поддержкой Java 2 ME в виде эмуляторов. Надо сказать, что количество мобильных устройств, где используется Java технология достаточно велико, посмотрите на список доступных моделей:
t
Телефонные эмуляторы
а 388 Simp. Chinese; а 388 Trad. Chinese; а 6288 Trad. Chinese; Q 6288 Simp. Chinese; а А008 East Europe; Q A008 North Europe; Q A008 Simp. Chinese; Q A008 South Asia; а А835; Q C353t;' О С370/С450/С550; а Е380; а Т280; а Т720; а А830; О v60; а v66; О А760; q A630; а С650; а Е398; а Т725; а V80;
О V189; а V220; а V300/V400/V500;
а V600.
,
Выберите из выпадающего списка в поле Handset телефонный эмулятор и далее укажите путь к приложению в поле Application. Путь можно задать вручную, а можно воспользоваться кнопкой Browse, выбрав директорию нахождения JAD и JAR файла, то есть программы написанной на Java. Путь нужно указывать к JAD-файлу. Затем нажмите на кнопку Lanch, на экране монитора появится выбранный телефонный эмулятор, а программа Motorola Lanchpad for J2ME автоматически закроется. Для того чтобы программа Motorola Lanchpad for J2ME не закрывалась каждый раз при запуске нового эмулятора, нужно поставит галочку в поле Keep Launchpad open after MIDlet Launch, после того как вы откроете программу Motorola Lanchpad for J2ME.
4.5. Программное обеспечение телефонов Samsung В папке \Samsung на компакт-диске найдите файл JSDKvl_0 - это программа установки. Инсталлируйте программу SamsungJSDK 1.0 на компьютер, а затем
Программное обеспечение телефонов Samsung J откройте установленную программу. Откроется основное окно Samsung JSDK 1.0, изображенное на рис. 4.15.
Рис 4.15. Программа Samsung JSDK 1.0 Для того чтобы запустить упакованную Java программу на телефонном эмуляторе поставляемом в пакете Samsung JSDK 1.0, выберите команду File => Import MIDlet и приложение будет запущенно. Очевидно, что телефонные эмуляторы значительно упрощают процесс разработки приложений, предоставляя разработчику универсальные средства для тестирования создаваемых программ. Представьте, какое количество денег нужно было потратить, для того чтобы приобрести несколько различных моделей телефонов. Но самое главное, пожалуй, это бесплатно распространяемое программное обеспечение, а также отсутствие дорогого лицензирования при создании программ на Java 2 ME. Любой программист из любого региона может бесплатно скачать необходимое программное обеспечение и заниматься разработкой своих собственных проектов при минимальных материальных затратах. В главах 3 и 4 вы изучили установку, настройку, работу с интегрированными средствами программирования приложений и инструментальными средствами
Телефонные эмуляторы пяти известных производителей телефонов. Поскольку в этих главах была представлена исчерпывающая информация по созданию, компиляции и запуску приложений с использованием различных программных средств, то в дальнейшем все внимание будет сосредоточено на изучении платформы Java 2 ME, В следующих главах.мы перейдем непосредственно к работе с кодом, где будет представлено для изучения большое количество интерфейсов, классов, методов из состава платформы Java 2 ME.
Глава 5. Механизм работы приложений Java 2 ME С этой главы начинается непосредственно описание работы с кодом. Специфика Java 2 ME приложений несколько своеобразна, но совсем не сложная. Достаточно разобраться в общей модели построения программ и все сразу станет понятно. В предыдущих двух главах вашему вниманию были представлены две среды программирования мобильных приложений и большое количество разнообразных телефонных эмуляторов. Полностью был разобран весь процесс установки этих средств, а так же режимы создания, компиляции кода и просмотр получившегося приложения на эмуляторе. Выберите себе понравившуюся среду разработки или работайте с теми средствами, к которым привыкли. Мы больше не будем отвлекаться на процесс написания кода, компиляции и запуска приложения на эмуляторе. Предшествующие две главы дали исчерпывающую информацию по этому поводу.
5.1. Мидлет Приложение, написанное для мобильного телефона, может состоять из различного количества классов. Одни классы, отвечают за загрузку ресурсов, другие за обработку данных, третьи выполняют еще какие-то дополнительные функции, как программист вы вправе выбирать любую удобную для вас модель построения программы. В итоге, созданные вами классы, объединенные в одно целое, будут составлять одну программу или приложение. Все приложения, сформированные для работы в'среде Java мобильных телефонов, носят название мидлет. Мидлет это программа, написанная для мобильного телефона с использованием платформы Java 2 ME. Определять количество классов программы привилегия программиста, но среди всех классов одной программы существует один основной класс, с которого начинается работа всей программы. Этот основной класс мидлета, сердце приложения, он наследуется от класса javax.microedition.midlet.MIDlet. В этом классе описывается код, отвечающий за управление процессом создания интерфейса пользователя, объявления набора данных необходимых для работы всего приложения, создаются объекты имеющихся классов, и что самое главное, он является отправной точкой в работе приложения. Такой класс в Java 2 ME носит название основной класс мидлета. Рабочие функции, выполняемые этим классом, практически идентичны методу main ( ) . Помните запись, с которой начинался рабочий процесс приложений написанных на Java 2 SE: public static void main ( String[] args )
f>
Телефонные эмуляторы
На мобильных устройствах аналогичные действия возложены на подкласс класса MI Diet, производящий управление рабочим процессом всего приложения. В дополнение к основному классу, может создаваться ряд классов необходимых для реализации поставленной перед вами задачи. Также имеется возможность собирать несколько мидлетов в один архив. Такая комплектация программ или мидлетов помещенных в один JAR-файл носит название MIDlet suite (набор мидлетов). В главе 2, когда объяснялась работа в среде Sun ONE Studio 4 Mobile Edition и J2ME Wireless Toolkit 2.1, в частности момент создания проекта Demo, был сформирован простейший код мидлета с названием HelloMIDlet. Этот код был сгенерирован автоматически Sun ONE Studio 4 Mobile Edition, он очень простой и дает хорошую возможность разобраться в структуре мидлета. Посмотрите на листинг 5.1, где приведен код примера HelloMIDlet проекта Demo, созданный в главе 2. На компакт-диске листинг находится в папке \Code\Listing5_l\src. /** Листинг 5.1 Класс HelloMIDlet.Java */ // импорт пакетов import javax.microedition.midlet.*; import javax.microedition.Icdui.*; , // создается класс HelloMIDlet public class HelloMIDlet extends MIDlet implements CommandListener { // команда выхода' из программы private Command exitCommand; // дисплей телефона private Display mydisplay; // конструктор класса HelloMIDlet public HelloMIDlet() { mydisplay = Display.getDisplayfthis); // выход из программы exitCommand = new Command(«Выход», Command.SCREEN, 2); } // входная точка приложения public void startAppf) / { //' объект класса TextBox TextBox t = new TextBox("HelloMIDlet","Текст",256, 0) ; // добавляет команду выхода t.addCommand(exitCommand);
Мидлет // устанавливает обработчик событий для команды выхода t.setCommandListener(this) ; // отражает текущий экран телефона mydisplay.setCurrent(t); // пауза в работе приложения public void pauseAppO {} // выход из программы public void destroyApp(boolean unconditional) {} // обработчик событий для команд приложения public void с ommandAct ion (Command с, Displaya'ble s) // обработка команды выход if. (с == exitCommand) {
// освобождает ресурсы и.выгружает из памяти мидлет destroyApp(false); notifyDestroyed() ; t, -
Первое, что бросается в глаза при детальном рассмотрении кода мидлета - это три метода: startApp ( ) - , pauseApp ( ) и destroyApp ( ) . Программисты, которые знакомы с аплетами, найдут явное сходство в структуре мидлета и аплета, даже названия в некоторой степени схожие. В аплете также имеются подобные методы: start ( ) , stop ( ) и destroy ( ) . Можно сказать, что основной класс мидлета - это некий симбиоз аплета и метода main ( ) , играющего основную и управляющую роль в приложении для мобильных устройств. Создавая свои классы и реализуя их код, вы должны возложить основные рабочие функции на основной класс мидлета. На рис. 5.1 показан принцип работы мобильных приложений.
Рис. 5.1. Принцип работы приложения
Механизм работы приложений Java 2 ME Сейчас мы вкратце разберем код примера HelloMIDlet проекта Demo, а потом перейдем к более детальному анализу схемы работы приложений в Java 2 ME. Первые две строки кода из листинга 5.1 - это библиотеки импорта. import j a v a x . m i c r o e d i t i o n . m i d l e t . * ; import javax.microedition.Icdui.*; В этих строках происходит импорт двух пакетов платформы Java 2 ME. Первый пакет javax.microedition.midlet.* содержит класс MIDlet, с помощью которого происходит связь с MIDP. Каждый код создающий основной класс мидлета обязан импортировать этот пакет. Второй пакет содержит классы, позволяющие создавать пользовательский интерфейс приложения. В следующей главе будут подробно рассмотрены все классы пользовательского интерфейса. Импорт двух пакетов дает возможность задействовать все имеющиеся в этих пакетах интерфейсы, классы, методы и константы, необходимые для работы всего создаваемого приложения. Следующая строка кода: public class HelloMIDlet extends MIDlet implements CommandListener создает основной класс мидлета, наследуемый от суперкласса MIDlet, реализуя при этом методы startAppO, pauseAppO и destroyApp(). Также задействуется интерфейс CommandListener, необходимый для обработки событий происходящих в приложении при помощи метода commandAction ( ) . Далее идут две строки создающие объекты классов Command и Display. private Command exitCommand; private Display mydisplay; С помощью переменной exitCommand осуществляется выход из приложения посредством метода commandAction(). Переменная mydisplay будет представлять дисплей телефона при помощи абстрактного класса Display, играющего роль диспетчера телефонных экранов. В конструкторе класса HelloMIDlet инициализируются объекты exitCommand и mydisplay. public HelloMIDlet() { mydisplay = Display.getDisplay(this); exitCommand = new Command!"Выход",Command.EXIT, 2 ) ; } В конструкторе класса HelloMIDlet, переменная mydisplay получает ссылку на объект Display при помощи метода getDisplay ( ) . Давайте разберемся эти действия подробно. Вы наверно заметили, что объект Display явно^не создается при помощи ключевого слова new. Если быть совсем точным, вы просто не можете этого сделать. Объект класса Display создается автоматически с помощью сервисов телефона для каждого мидлета. Класс Display играет роль диспетчера телефонных экранов, на которые проецируется в итоге все то, что вы бу-
Мидлет
ниш
дете видеть на дисплее телефона. .В телефоне существует всего один основной экран и поэтому в отдельный промежуток времени может быть отражен только один экран, за который отвечает класс Display. С помощью метода getDisplay ( ) , основной класс мидлета получает ссылку на класс Display и содержит ее в переменной mydisplay. В последствии, для того чтобы отразить содержимое текущего дисплея, необходимо воспользоваться методом setCurrent (•), например следующим образом: mydisplay.setCurrent() ; Вторая и последняя строка кода в конструкторе класса HelloMIDlet ( } создает экземпляр класса Command и инициализирует созданный ранее объект exitCommand. Класс Command создает набор информации или набор команд, которые можно отобразить на экране телефона для обработки событий полученных от пользователя. На основе определенного набора команд с помощью интерфейса CommandListener происходит обработка фактических действий пользователя. Посмотрите на рис. 5.2, где на дисплее показана команда Выход, расположенная под экранной клавишей телефона. Такая схема отображения различных команд реализована на всех без исключения мобильных телефонах. Единственное, что может изменяться - это способ отображения этих команд. У некоторых производителей мобильных телефонов команды располагаются под экранными клавишами, а у других, ряд команд формируется в виде меню. Класс Command имеет два конструктора с тремя и четырьмя параметрами. В примере был использован конструктор из трех параметров, посмотрим, как Рис. 5.2. Команда выглядит прототип конструктора класса Command: выхода из программы public Command( String label, int commandType, int priority ) Параметры конструктора класса Command: Q label - это переменная типа String, содержащая метку в виде простого текста: В примере использовалась команда Выход. Эта строка текста может находиться под кнопками дисплея, либо в виде элемента меню. Обычно команда - это короткое слово. Если необходимо использовать длинное слово, то нужно вызвать конструктор класса Command с четырьмя параметрами; O commandType - тип команды соответствующей выбранным действиям.
t
Cl Q Q Q
Имеются команды BACK, CANCEL, EXIT, HELP, ITEM, SCREEN, STOP. BACK - возврат к предыдущему экрану; CANCEL - отмена произведенных действий; EXIT - выход из приложения; HELP - вызов справки;
\
Механизм работы приложений Java 2 ME Q ITEM - обычно используется для работы с классом Choice, и производит выбор элемента из группы элементов; Q SCREEN - представление нового экрана; О STOP - остановка выполняемых действий. Q priority - это приоритет, назначенный для данной команды относительно других команд, имеющихся на дисплее. Приоритет задается -целым числом, где более низкое число указывает на более высокое значение. За конструктором класса HelloMIDlet ( ) следует ключевой метод основного класса мидлета startApp ( ) . public void s t a r t A p p ( ) { TextBox t = new TextBox{"HelloMIDlet","Текст",256, 0 ) ; t.addCommand(exitCommand); t.setCommandListener(this) ; mydisplay.setCurrent(t); } Метод startApp () вводит приложение в активное состояние и является своего рода выходной точкой для всей программы. В рассматриваемом примере для вывода текста на экран используется класс TextBox. Чтобы разобраться, как это происходит, необходимо рассмотреть конструктор класса TextBox: public TextBox (String t i t l e , String text, int naxSize, .int constraints) Параметры конструктора класса TextBox: Q t i t l e - это титл или основное название, размещенное в верхней части дисплея; Q text - текст, выводящийся непосредственно на экран. Текст, выводимый на экран можно редактировать и даже не выводить вовсе, выставив значение этого параметра в значение null; О maxSize — максимальное количество символов выводимого на экран текста; Q constraints - с помощью этого параметра можно производить специальные ограничения, но пока рекомендую выставить параметр в 0. То есть, создав объект класса TextBox, вы задаете область экрана, в которой существует свое название и количество выводимых символов. В следующих двух строках кода: t.addCommand(exitCommand); t.setCommandListener(this); сначала добавляется команда Выход, к текущему экрану телефона представленному классом TextBox, а затем с помощью метода setCommandListener ()
Мидлет устанавливается обработка событий для этой команды Выход, используя метод интерфейса CommandListener . Самая последняя строка кода: mydisplay .setCurrent (t } ; отражает текущую информацию на экране. Этот метод подобен кнопке Обновить в Internet Explorer. Вызывая каждый раз метод setCurrent ( ) , вы будете обновлять информацию на дисплее телефона. Следующий метод в примере: public void p a u s e A p p ( ) Тело этого метода пока отсутствует, но с его помощью можно поместить мидлет в состояние паузы и освободить часть используемых ресурсов приложения. Дальше идет метод destroyApp ( ) , освобождающий захваченные мидлетом ресурсы и удаляющий сам мидлет из памяти, то есть закрывает работу приложения. И самый последний метод основного класса мидлета commandAction ( ) интерфейса CommandListener обрабатывает назначенные события. public void commandAction (Command c, Displayable s) { •if (c == eXitCommand)
£ destroyApp (false) ; notifyDestroyed( ) ;
По сути, этот метод является обработчиком событий приложения для всех имеющихся команд. В нашем примере происходит обработка команды Выход. После чего происходит освобождение всех захваченных ресурсов и мидлет выгружается из памяти с помощью методов destroyApp ( ) и notifyDestroyedf ) . Рассмотрев вкратце общую модель работы мидлета, давайте разберем более подробно процесс работы приложений, а также жизненный цикл всей программы.
5.1.1. Модель работы мидлета После успешной компиляции примера HelloMIDlet и запуска на любом понравившемся вам эмуляторе, на дисплее эмулятора в верхнем левом углу появится надпись HelloMIDlet. В нашем случае мидлет всего один, но возможна ситуация когда будет несколько мидлетов, то есть MIDlet suite (набор мидлетов), тогда сервис телефона автоматически создаст меню выстроив все имеющиеся мидлеты друг под другом, предоставляя возможность в выборе программы. Но это не значит, что после того, как вы войдете в ваше приложение, сервис телефона и далее будет так же создавать за вас меню. Нет, действия по структуризации приложения, созданию списков и меню лежит на плечах программиста. На рис. 5.3 изображено меню телефона с набором различных программ. Для того чтобы запустить программу на эмуляторе, необходимо нажать кнопку Select (выбор), после чего вы попадаете непосредственно в рабочий цикл при-
•
Механизм работы приложений Java 2 ME Рис. 5.3. Меню1 в телефоне Phone
Zoom
ОеЬиддюдДгасйтд
ложения. После нажатия клавиши Select, то есть подачи команды активизации приложения, в мидлете происходит поиск метода s t a r t A p p O , который является начальной и входной точкой всех программ. И уже в методе startApp ( ) идет обработка соответствующего программного кода и как следствие, выполнение работы приложения. Конечно, код находящийся до метода startApp ( ) : объекты, конструктор и так далее, так же инициализируются, но активизация рабочего процесса мидлета происходит с вызовом метода startApp ( ) . В рассматриваемом примере мы воспользовались классом TextBox, который создает область для вывода текста. В связи с этим, на экране появится текстовая строка, изначально прописанная в программном коде в параметре text конструктора класса TextBox. Этот текст на дисплее можно отредактировать как угодно, воспользовавшись клавишами эмулятора телефона. В нижнем левом углу экрана, вы увидите надпись Выход. Нажав на клавишу телефона под этой надписью, вы автоматически выйдете из программы. При нажатии подэкранной клавиши Выход, происходит запуск метода commandAction(), реакция которого на команду Выход, равносильна обработке событий для переменной exitCommand. Обработка события в данном случае подразумевает вызов двух методов - destroyApp ( ) и notifyDestroyed(), благодаря которым происходит обнуление ссылок, если таковые имеются, и выгрузка мидлета и всего приложения из памяти телефона, возвращая вас в меню телефона, откуда производился запуск рассматриваемой программы. В итоге весь жизненный цикл работы приложения сводится к периоду активизации программы до выхода из нее. На рис. 5.4 показана общая модель работы мидлета. Основной класс мидлета - это своего рода мотор всего приложения, тогда как функциональную часть лучше разбить на необходимое количество классов. Конечно, возможна интеграция всего программного кода приложения в код основного класса мидлета, но, во-первых, это непрофессионально, а во-вторых, это просто неудобно. Хорошо если вы пишете совсем маленькое приложение подобно нашему примеру, но когда речь идет о более серьезном программном, продукте, надо разработать четкую структуру классов, продумать общую модель взаимодействия и в конечном итоге написать код приложения. При рассмотрении примеров этой и следующей главы мы будем пока использовать основной класс мидлета, формируя Рис. 5.4. Модель работы мидлета в этом классе дополнительные объекты рассматHelp
Пользовательский интерфейс риваемых классов платформы Java 2 ME, для того чтобы не путаться в большом количестве исходных файлов. Но, начиная с главы 7, перейдем к профессиональной модели построения приложений.
5.2. Пользовательский Интерфейс Когда мы рассматривали механизм работы примера из листинга 5.1, я думаю, вы подметили некий поэкранный принцип отображения информации на дисплее. Первый экран показывал список доступных приложений, после выбора одного из них вы попадали на экран этого приложения. Нажав кнопку Выход, происходило возвращение к экрану выбора. В Java 2 ME программах такая схема поэкранного отображения информации является основной. Если вы никогда не обращали на это внимания при работе со своим телефоном, то самое время взять его и пощелкать джойстиком. В приложениях для мобильных телефонов основанных на экранах в Java 2 ME отсутствуют окна и фреймы в отличие от Java 2 SE. Телефоны ограничены в системных ресурсах и разнообразная красивая роскошь, к сожалению не позволительна для этих маленьких устройств. Поэтому при создании конечного продукта стоит с особой тщательностью продумывать основные составляющие будущего приложения. Основываясь на поэкранном отображении информации, необходимо создавать интуитивно понятную структуру приложения, образуя при этом четкую экранную навигацию. Если пользователь заблудится в вашей программе, он просто удалит ее из памяти телефона и никогда к ней больше не вернется, а вы потеряете потенциального покупателя. Как уже отмечалось, экран телефона представлен классом Display. Каждый мидлет может иметь только один объект класса Di splay, возвращаемый мидлету при помощи метода getDisplay ( ) .определяя тем самым текущий дисплей телефона для мидлета. Платформа Java 2 ME обладает пакетом javax.microedition.lcdui, включающим в себя классы для работы с пользовательским интерфейсом UI (user interface). Большое количество классов, входящих в этот пакет, будут подробно рассматриваться в следующей главе. Самым главным классом пользовательского интерфейса является класс Displayable. С основы абстрактного класса Displayable происходит построение основной части графического интерфейса приложения. На рис. 5.5 показана структура пользовательского интерфейса пакета javax.microedition.lcdui. От класса диспетчера Display зависит, какой из классов Displayable будет отображен на экраРис. 5.5. Структура пользовательского интерфейса
I
Механизм работы приложений Java 2 ME
не. В свою очередь только один класс Displayable может быть единовременно показан на экране. То есть, объект класса TextBox, грубо говоря, существует в своем экране, объект класса List - в своем и оба объекта не могут существовать вместе на одном экране, определяя тем самым правило поэкранного отражения информации на дисплее телефона. Далее в иерархии структуры пользовательского интерфейса, показанного с помощью рис. 5.5, идут два абстрактных класса: Screen-и Canvas. На этой стадии происходит разделение классов пользовательского интерфейса на высокоуровневый класс, назначенный классу Screen и всей его дальнейшей иерархии наследования и низкоуровневый класс Canvas. Оба класса создают структуру интерфейсов, разделенную на высокоуровневый и низкоуровневый пользовательский интерфейсы. Высокоуровневый интерфейс содержит средства для работы с пользовательским интерфейсом, созданные на основе классов шаблонов, использование которых приводит к построению жестко заданного интерфейса. Например, задействованный в исходном коде HelloMIDlet проекта Demo класс TextBox, не может никаким образом изменить экран телефона. Экран представленный классом TextBox - это текстовый контейнер, в котором можно осуществлять вывод, удаление и редакцию текста и не более того. То есть классы высокоуровневого интерфейса - это жестко заданная модель отображения пользовательского интерфейса на экране телефона, с помощью которых программист организует навигацию, списки, меню, текстовые контейнеры, группы выбираемых элементов и так далее. Низкоуровневый интерфейс предоставляет графические средства для рисования на экране различных графических элементов и обработку команд, посылаемых с клавиш телефона. Низкоуровневый интерфейс позволяет рисовать на экране телефона, добавляя тем самым в приложение красивые графические элементы в виде таблицы, изображений, полей, заставок и так далее. Такое разделение классов существует сугубо в теоретическом виде и ничто вам не мешает комбинировать элементы обоих интерфейсов в одной программе, создавая красивое интерактивное приложение. На рис. 5.5 была дана часть пакета javax.microedition.lcdui.*, потому что классы Canvas и GameCanvas будут подробно рассматриваться соответственно в главах 7 и 8. Рассмотрим некоторые характеристики классов Alert, TextBox, Form и List представляющие высокоуровневый интерфейс: Q Alert - предоставляет возможность в создании уведомлений или сообщений об ошибках в виде отдельных экранов; Q TextBox - массив данных содержащий текстовую информацию с возможностью ее редакции; Q Form - экранньш контейнер, в котором можно разместить различные элементы интерфейса с помощью дополнительных подклассов класса Item; Q List - список элементов, позволяющий производить выбор различных операций.
Переход с экрана на экран
5.3. Переход с экрана на экран Прежде чем мы приступим к изучению основ перехода в приложении с одного экрана на другой, хочу обозначить стоящие перед нами задачи в рассмотрении средств по созданию пользовательского интерфейса. Сейчас вы имеете некоторое представление о модели работы программ для мобильных телефонов. Далее вы изучите основной способ перехода от экрана к экрану внутри приложения на простом примере. Потом код несколько усложнится и будет показан механизм навигации в программах на Java 2 ME. И уже в главе 6 будут изучены все классы пользовательского интерфейса для создания действительно красивых программ. Сейчас мы идем от простого к сложному и я хочу предложить вам новый пример кода/на основе которого будет изучена схема перехода с одного экрана на другой. Попутно мы задействуем все четыре высокоуровневых класса TextBox, Form, List и Alert. Прежде чем коснуться непосредственно программирования любого приложения, нужно уделить внимание теоретической части создаваемой программы. Лично я, когда разрабатываю некую программу для мобильного телефона, беру чистый листок бумаги, карандаш и рисую предполагаемый набор экранов, указывая на связь между ними с помощью стрелочек. Это, конечно, не язык UML, но достаточно просто и эффективно. На рис. 5.6 даются все четыре дисплея и связь между ними.
Рис. 5.6. Переход с экрана на экран Идея этого показательного примера очень проста. Первым делом после входа в приложение вы попадаете в класс Form, являющимся неким контейнером для элементов пользовательского интерфейса. В этом примере классы Form, List, TextBox и Alert не задействованы в полном объеме, а только показывают информативную надпись названия класса. После попадания на экран представленного классбм Form, появятся две кнопки: выхода из программы и переход на следующий экран представленный классом TextBox. После перехода с экрана представленного классом Form в TextBox, на экране появится две кнопки: выход из приложения и переход. Кнопка перехода приведет вас на экран представленный классом List, дав аналогичную возможность выбора перехода. Выбрав переход на экран представленный классом Alert, вы увидите на некоторое время
.
Механизм работы приложений Java 2 ME экран с надписью Alert и автоматически возвратитесь в List. По своей специфики класс Alert предназначен для сообщения информации об ошибке или исключительной ситуации, этим объясняются и соответствующие действия этого класса. Приступим к написанию кода этого примера. Первым делом импортируем две библиотеки: import javax.microedition.midlet.*; import javax.microedition.Icdui.*. Затем создаем класс Perexod, наследуемый от класса MIDlet. public class Perexod extends MIDlet implements CbmmandLi s t ener Теперь необходимо создать объекты класса Command. Объект exitMidlet нужен для выхода из программы. Код, реализующий это событие аналогичен коду из предыдущего примера, рассмотренного в листинге 5.1. И еще три объекта будут служить для перехода от экрана к экрану: /
private private private private private
Command exitMidlet; Command perexodTextBox; Command perexodList; Command perexodAlert; Display mydisplay;
Названия этих объектов достаточно информативны и в объяснении не нуждаются. Далее очередь подошла к конструктору класса Perexod. Первым делом сохраним ссылку на Display в переменной mydisplay: mydisplay = Display.getDisplay(this); Следующим шагом создадим два объекта класса Command, один для выхода из программы, другой для перехода на экран представленный классом Text Box. exitMidlet = new Command("Выход", Command.EXIT, 1); perexodTextBox = new Command("Перейти", Command.SCREEN,
2)';
Создание эти* объектов в конструкторе - не обязательное условие. Просто я основывался на предыдущем примере и оставил примерную структуру приложения для понимания. На самом деле все четыре объекта класса Command можно было инициализировать еще при их объявлении в начале класса MainMidlet, что более читабельно. Следующим кодом за конструктором идет метод startАрр ( ) , внутри которого создается объект класса Form. Добавим при помощи метода addCommand ( ) команду Выход - это выход из приложения и команду Переход - это переход на экран представленный классом TextBox. Назначим обработчик событий классу Form методом setCommandListener ( ) и присоединим объект myform класса Form к текущему дисплею при помощи метода setCurrent().
Переход с экрана на экран public void s t a r t A p p ( } { Form my form = new F o r m ( " Э т о объект класса F o r m " ) ; myform.addCommand(exitMidlet); my form.addCommand't perexodTextBox) ; myform.setCommandListener(this); // отражает текущий экран mydisplay.setCurrent(myform); }
Когда вы запустите программу или войдете в рабочий цикл мидлета, то автоматически инициализируются объекты классов и конструктор класса Perexod, а работа программы начнется с вызова метода startApp ( ) . Теперь необходимо назначить соответствующие действия клавишам перехода в методе commandAction ( ) интерфейса CommandListener для обработки пользовательских команд. Переход по кнопке Выход вам уже знаком из предыдущего примера, поэтому оставим все почти без изменения, за исключением информационной команды exitMidlet. if (с == exitMidlet) -С. destroyApp(false); notifyDestroyed(); } А теперь вплотную займемся командой Перейти. Что от нас требуется? В момент запуска программы мы попадаем на экран представленный классом Form посредством команды perexodTextBox, а требуется прейти на'экран представленный классом TextBox. Для создания обработчика событий команды Перейти нужно сформировать объект класса TextBox, позаботиться о следующей кнопке перехода perexodList для перехода на экран, представленью классом List, добавить команду Выход для выхода из программы и команду Перейти. Осталось добавить обработчик событий и присоединить созданный TextBox к текущему экрану. Смотрим, что у нас получилось: if (с == perexodTextBox) ( TextBox tb = new TextBox("TextBox", "Текст", 256, 0); perexodList = new Command("Перейти", Command.SCREEN, 2); tb.addCommand(exitMidlet); tb.addCommand(perexodList) ; tb. setCommandListener (this)";' Display.getDisplay(this).setCurrent(tb);
|(
Механизм работы приложений Java 2 ME
Обратите внимание на последнюю строку кода в теле условного оператора i f: Display.getDisplay(this).setCurrent(tb); В данном случае присоединяется созданный объект tb класса Text Box к текущему экрану. Мы говорим о смене экранов для создания четкого и информативного пользовательского интерфейса, на самом деле смены экранов в буквальном смысле не происходит. Существует только один дисплей, назначенный для класса Di spl ey, который отвечает за то, что будет нарисовано на экране телефона, а именно, какой из объектов Displayable. Только один объект Displayable может быть отображен за один раз на экране. То есть существует всего один физический дисплей, к которому присоединяются необходимые объекты классов пользовательского интерфейса через обработку событий. Имеющийся экран просто постоянно перерисовывается, отображая тот или иной объект востребованного класса, а иначе говоря, к текущему дисплею присоединяется объект класса, создавая иллюзию смены экранов. Системные ресурсы телефонов пока малы, поэтому приходится идти на такие хитрости. Затем в рассматриваемом примере необходимо перейти на экран представленный классом List. Поскольку мы имеем аналогичные требования к экземпляру этого класса, то обработка событий и создание класса List будут идентичными классу TextBox. if (с == perexodList)
'{ List mylist = new L i s t ( " L i s t " , List.IMPLICIT) ,• perexodAlert = new Command("Перейти", Command.SCREEN, 2 ) ; mylist.addCommand(exitMidlet); mylist.addCommand(perexodAlert); mylist.setCommandListener(this); Display.getDisplay(this).setCurrent(mylist);
} Позаботившись о переходе на экран представленный классом Alert и о выходе из приложения, можно создать код для объекта Alert, который впоследствии можно присоединить к текущему экрану. Класс Alert несколько специфичен, это вам станет понятно как только вы откроете окно, отвечающее за отображение объекта. Попробуйте после компиляции рассмотренного примера сделать для Alert команду Выход, и посмотрите, что получится. Теперь соединим рассмотренный код в одно целое, получив готовую программу, представленную в листинге 5.2; Пример также можно найти на прилагаемом к книге компактдиске в папке \Code\Listing5_2\src.
/** Листинг 5 . 2 Переход с экрана на экран */ // подключаем пакеты
Переход с экрана на экран import javax.microedition.midlet .*; import javax.microedition. icdui . *; // создаем класс Perexod public class Perexo<^ extends MIDlet implements CommandListener { // команда выход из программы private Command exitMidlet; / / команда перехода в программе private Command perexodTextBox; private Command perexodList ; private Command perexodAlert; / / дисплей private Display mydisplay; // конструктор класса Perexod public Perexod () i { mydisplay = Display. getDisplay (this) ; // выход из приложения exitMidlet = new Command (" Выход ", Command. EXIT, 1); t II переход TextBox perexodTextBox = new Command (" Перейти ", Command . SCREEN , 2); // входная точка всей программы public void startAppO // создаем объект класса Form Form myform = new Form ("Это объект класса Form"); // добавляем команду выхода из программы my form.addCommandf exitMidlet) ; // добавляем команду перехода в TextBox ту form.addCommand (perexodTextBox) ; // устанавливаем обработчик событий для команд объекта класса Form myform. setCommandListener ( this) ; / / отражаем текущий экра.н mydisplay .setCurrent (myform) ; public void pauseApp ( ) { } public void destroyApp (boolean unconditional) {} // обработчик событий в программе public void commandAct ion (Command c, Displayable d)
Механизм работы приложений Java 2 ME / / обработка команды выход if (с == exitMidlet) { destroy App( false) ; notifyDestroyed( ) ; } // обработка команды перехода в TextBox if (с == perexodTextBox) { TextBox tb = new TextBox ( "TextBox" , "Текст", 256, 0);. perexodList = new Command ( "'Перейти ", Command. SCREEN, 2) ; tb . addCommand ( exitMidlet) ; tb . addCommand ( perexodList) ; tb.setCommandListener (this) ; Display .getDisplayf this) .setCurrent (tb) ; } // обработка команды перехода в List if (с == perexodList) { List mylist = new ListC'List", List .IMPLICIT) ; perexodAlert = new Command (" Перейти ", Command . SCREEN , 2);
mylist .addCommand (exitMidlet) ; mylist .addCommand (perexodAlert) ; mylist .setCommandListener (this) ; Display .getDi splay (this) .setCurrent (mylist) ; } // обработка команды перехода в Alert if (с '== perexodAlert) { Alert myalert = new Alert ( "Alert" , "Текст" ,null, null) ;, Display .getDisplay( this) .setCurrent (myalert) ;
После компиляции примера пройдите по всей программе и убедитесь, что вам понятна общая идея и принцип работы смены экранов, на которых строятся все приложения в Java 2 ME.
5.4. Навигация Рассмотренный пример из листинга 5.2 раскрыл суть перехода с одного экрана на другой. Как вы заметили, принцип смены экраны довольно прост - доста-
Навигация точно добавить необходимую команду с помощью метода addCommand (.), установить обработчик событий для этого экрана и создать код в методе commandAction ( ) , адекватно реагирующий на заданные действия. Познакомившись с моделью смены экранов и закрепив свои знания на практике, можно переходить к более осмысленной навигации в приложении. В предыдущем примере происходила последовательная смена экранов без возможности возврата либо перехода на необходимый экран. Такая структура хороша для изучения, но абсолютно не годится для серьезного приложения. Телефоны различных марок имеют собственные механизмы перехода, предоставляемые операционной системой или прошивкой мобильного телефона. Механизм, использованный в Java 2 ME для приложений созданных на этом языке, предоставляет не менее мощные, а главное, простые средства для навигации в программе. Самый простой и, как мне кажется, эффективный способ - это использовать автоматически созданное меню при помощи сервиса телефона. Когда вы добавляете к заданному экрану с присоединенным к нему объектом Display able команды обработки в виде двух подэкранных клавиш, вы имеете всего два видимых варианта клавиш слева и справа. Как только вы добавите с помощью функции addCommand ( ) более двух команд, сервис телефона автоматически создаст на правой или левой подэкранной клавише телефона (в зависимости от марки производителя), выпадающее меню. При нажатии клавиши, отвечающей за меню, появится меню, отображающее полный список имеющихся команд. На рис. 5.7 изображено контекстное меню, созданное эмулятором телефона среды программирования J2ME Wireless Toolkit 2.1. Задав нужные команды для конкретного объекта Displayable, и создав код их обработки, вы получаете отличный механизм навигации. Но это не единственный способ перехода с экрана на экран. Каждый из четырех классов Form, List, TextBox и Alert имеет свои встроенные средства для создания списков, меню, таблиц, полей, загрузки изображений и так далее. При знакомстве с каждым из классов мы обязательно рассмотрим имеющиеся возможности. А пока давайте разберем механизм автоматического создания меню и обработки имеющихся команд. Итак, к каждому из задействованных классов нам надо добавить набор команд для перехода на нужный экран и обработать, а точнее, создать код, реагирующий на назначенные команды. Рис. 5.8 живописно изображает и отчасти решает поставленную перед нами задачу. Теперь сосредоточимся на одном из вариантов программного кода, решающего проблему с навигацией. Первым делом создадим класс, назвав его Navigator. public class Navigator extends MIDlet implements CommandListener Рис. 5.7. Автоматически созданное меню
Механизм работы приложений Java 2 ME
к
Form
Л
Переход в TextBox Переход в List Переход в Alert
ч г
A
TextBox
List Переход» Form Переход в TextBox Переход в Alert
Переход • Form Переход в List Переход в Alert
t
Э
ь
Alert
Рис. 5.8. Схема перехода с экрана на экран В исходном коде до строк вызова конструктора класса Navigator, добавим объект, содержащий команду Выход. private Command exitMidlet = new Command("Выход", Command.EXIT, 1); Потом необходимо создать четыре объекта для каждого из задействованных классов Form, TextBox, List и Alert. Созданные объекты будут отвечать за обработку команд перехода на экран, представленные соответствующими классами. private Command Command.SCREEN, private Command Command.SCREEN, private Command Command.SCREEN, private Command Command.SCREEN,
perexodTextBox = new Command("В TextBox", 2); perexodList = new Command("B L i s t " , 2); perexodAlert = new Command("B Alert", 2) ; perexodForm = new Command("B Form", 2) ;
Информативные названия всех объектов понятны, но, естественно, выбранные мною названия ни к чему вас не обязывают. Созданные объекты являются объектами класса Command, отвечающего за создание команд, которые в последствии можно определить для каждого из классов Form, TextBox, List и Alert. Позже, в коде мидлета, мы будем задавать соответствующие блоки обработки событий непосредственно в методе commandAction ( ) при помощи оператора if и созданных объектов. Теперь нам нужно объявить и инициализировать объекты четырех классов Form, TextBox, List и Alert. private Form myform = new Form("Это объект класса Form"); private List mylist = new L i s t ( " 3 T O объект класса L i s t " , List.IMPLICIT); private TextBox mytextbox = new TextBox("Это TextBox", "Текст", 256, 0 ) ;
Навигация private Alert myalert = new A l e r t ( " Э т о A l e r t " , исчезнет",null,null); private Display mydisplay;
"Alert
В конструкторе класса Navigator происходит инициализация объекта mydisplay. public Navigator() { mydisplay = Display.getDisplay(this); } Следующая наша задача - это реализация метода startАрр ( ) . Сейчас необходимо решить какой из классов будет первым появляться на экране и добавить к нему команды перехода в другие классы, а также команду выхода из приложения. В предыдущем примере первым появлялся класс Form. Его и определим как основной объект, в который попадет пользователь, запускающий приложение. public void startAppO { myform.addCommand(exitMidlet); myform.addCommand(perexodTextBox); myform.addCommand(perexodList); myform.addCommand(perexodAlert); myform.setCommandListener(this); mydisplay.setCurrent(myform); } Последняя строка метода startApp ( ) отображает объект myform на дисплее со всеми имеющимися командами. Как уже говорилось, командам, которым не хватит телефонных клавиш,будет автоматически создано свое собственное меню. После того как вы попадете в основное окно приложения, которое мы определили для объекта myform, над левой или правой подэкранной клавишей появится команда выхода из приложения и команда Menu. При нажатии на клавишу Menu, на экране телефона появится всплывающее меню с добавленными ранее командами перехода на экраны, представленные классами Text Box, List и Alert, Следующей нашей задачей является написание кода для обработки событий созданных команд в методе commandAction ( ) . Код, обрабатывающий команду Выход из приложения, идентичен коду из примера в листинге 5.2 и в большинстве рассматриваемых впоследствии примеров останется таковым. Дальнейшие действия состоят в обработке команды перехода на экран, представленный классом TextBox. if (с == perexodTextBox) •{ mytextbox.addCommand(exitMidlet);
Механизм работы приложений Java 2 ME mytextbox.addCorranand(perexodForm); mytextbox.addCommand(perexodList-) ; mytextbox.addCommand(perexodAlert); mytextbox.setCommandListener(this); mydisplay.setCurrent(mytextbox);
} Сразу после того, как пользователь попадет на экран, представленный классам Form, и в контекстном меню выберет команду Перейти в TextBox, произойдет обработка блока команд perexodTextBox. Добавляются все команды к объекту mytextbox, устанавливается обработчик событий и в итоге отображается текущий экран, содержащий все созданные компоненты объекта mytextbox. Точно так же как и на экране с объектом my form существует меню перехода и кнопка выхода. Обработка событий для объекта mylist происходит с помощью команды perexodList и аналогично рассмотренному коду для объекта mytextbox. С той лишь разницей, что используются соответствующие команды для объекта mylist. В итоге листинг 5.3 связывает все разрозненные фрагменты кода этого подраздела, собирая воедино очень простую и в то же время, мощную программу отличной системы навигации. /**
Листинг 5.3 Навигация в приложении */ import javax.microedition.midlet.*; import javax.microedition.Icdui.*; public class Navigator extends MIDlet implements CommandListener { // команда выхода из приложения. private Command exitMidlet = new Command("Выход", Command.EXIT, 1); // команда перехода в TextBox . private Command perexodTextBox" = new Command("B TextBox", Command.SCREEN, 2) ,// команда перехода в List private Command perexodList = new Command("B List", Command.SCREEN, 2); //. команда перехода в Alert private Command perexodAlert = new Command("B Alert", / Command.SCREEN, 2) ; // команда перехода в Form
Навигация private Command perexodForm = new Command ("B Form", Command , SCREEN , 2 ) ,// объект класса Form private Form myform = new Рогт("Это объект класса Form") // объект класса List private List mylist = new List ("Это объект класса List", List. IMPLICIT) ; //^объект класса TextBox private TextBox mytextbox - new TextBox("3TO TextBox", "Текст" , 256, 0) ; // объект класса Alert private Alert myalert = new Alert ("Это Alert" , "Alert исчезнет" , null , null) ; // объект mydisplay представляет экран телефона private Display mydisplay; public Navigator () { mydisplay = Display .getDisplay( this) ;
public void startAppO .{ // добавить команды перехода в Form myform.addCommand(exitMidlet) ; myf orm.addCommand(perexodTextBox) ; myform.addCommand(perexodList) ; myform.addcommand (perexodAlert) ; // установка обработчика событий -для Form myform.setCommandListener (this) ; // отразить текущий дисплей mydisplay .setCurrent (myform) ;
public void pauseApp ( ) {} public void destroy App (boolean unconditional) {} public void commandAct ion (Command c, Displayable d) { / / выход из приложения if (с == exitMidlet) { destroy App (f.alse) ; notifyDestroyed ( ) ;
Механизм работы приложений Java 2 ME //.переход в TextBoxif (c ==,perexodTextBox) mytextbox.addCommand(exitMidlet); mytextbox.addCommand(perexodForm); mytextbox.addCommand(perexodList); mytextbox.addCommand(perexodAlert); mytextbox.setCommandListener(this); mydisplay.setCurrent(mytextbox); // переход в List if (c == perexodList) mylist.addCommand(exitMidlet); mylist.addCommand(perexodForm); mylist.addCommand(perexodAlert); mylist.addCommand(perexodTextBox); mylist. setCommandListener (this) ; mydisplay.setCurrent(mylist);
; ••'
// переход в Alert if (c ==. perexodAlert) mydisplay.setCurrent(myalert); // переход в Form if (c == perexodForm) mydisplay .setCurrent'(my form) ;
} } В следующей главе будут изучаться классы высокоуровневого интерфейса, с помощью которых создаются списки, группы элементов, текстовые поля и множество других элементов пользовательского интерфейса.
Глава 6. Классы пользовательского интерфейса В Java 2 ME имеется пакет javax.microedition.lcdui, определенный для классов пользовательского интерфейса. Как уже отмечалось в главе 5, классы пользовательского интерфейса разделены на высокоуровневый и низкоуровневый интерфейсы. В этой главе будут последовательно рассмотрены все классы высокоуровневого пользовательского интерфейса. Каждый из разделов содержит информацию об одном конкретном классе, предоставляющем ряд возможностей в оформлении интерфейса пользователя. Используя возможности этих классов, вы сможете создавать в приложении списки, группы элементов, загружать в программу изображения, использовать бегущую строку, назначать шрифт текста и многое другое. В разделах по каждому классу пользовательского интерфейса, анализируются конструкторы, основные методы и константы класса, с помощью которых в конце каждого раздела создается приложение, иллюстрирующее работу этого класса', и приводится листинг всей программы. При рассмотрении методов и констант классов используется только основные компоненты. Для детального анализа составляющих одного из классов обратитесь к приложению 2, которое выполнено в виде справочника по Java 2 ME. Единственное, о чем необходимо помнить при проектировании и создании пользовательского интерфейса приложения - это об используемом профиле MIDP. В некоторые классы, имеющиеся в составе профиля MIDP 1.0, были добавлены новые методы, константы и даже классы из профиля MIDP 2.O. Например, в классе ChoiceGroup для профиля MIDP 1.0 доступно тринадцать методов, а уже в профиле MIDP 2.0 их насчитывается семнадцать, то есть, добавлено еще четыре новых. В той же документации по Java 2 ME какой-то четкой грани разделяющей два профиля не существует, но при рассмотрении методов и констант упоминается о принадлежности к одному из профилей. Поэтому при создании приложений, например под профиль, MIDP 1.0, необходимо внимательно планировать разработку программ и не задействовать компоненты профиля MIDP 2.0. Если вы разрабатываете программу для профиля MIDP 2.0, то можете пользоваться всеми имеющимися компонентами вне зависимости от принадлежности к одному из профилей.
6.1. Класс Form Основным экранным классом примеров из главы 5 служил экран, представленный классом Form. Как вы понимаете это не обязательное условие, но я выбрал класс Form не случайно. Дело в том, что реализация класса Form выполнена
I!
Механизм работы приложений Java 2 ME
в виде контейнера, позволяющего встраивать в себя различные компоненты пользовательского интерфейса. Это, пожалуй, единственный и самый мощный по своим возможностям класс. Само по себе название Form подразумевает создание некой формы для заполнения экрана телефона. В предыдущих примерах мы использовали, так называемую, пустую форму этого класса в виде чистого экрана. Впоследствии, при упоминании термина форма, будет подразумеваться экран телефона, представленный объектом класса Form для интеграции классов пользовательского интерфейса. Класс Form имеет два конструктора, необходимых при создании объекта этого класса. Первым конструктором мы уже пользовались, и выглядит он достаточно просто: public Form (String title) Параметры конструктора класса Form: О title - заголовок появляется в верхней части созданного окна. Второй конструктор класса Form имеет уже два параметра, и позволяет встроить компоненты интерфейса в пустую форму, public Form (String title, Itein[] items) Параметры конструктора класса Form: Q t i t l e - заголовок окна; Q items - массив компонентов размещаемых в классе Form. В классе Form существует набор методов, с помощью которых можно добавить, удалить или вставить компоненты интерфейса. Класс Form имеет двенадцать методов, с помощью которых можно манипулировать компонентами абстрактного класса Item. Всего насчитывается восемь компонентов пользовательского интерфейса в иерархии класса Item. To есть вы создаете экран, за который отвечает класс Form, и интегрируете имеющиеся в вашем распоряжении компоненты класса Item. О самом классе Item и его иерархии мы поговорим в следующем разделе этой главы, после анализа класса Form.
6.1.1. Методы класса Form Q int append (Image img) - добавляет в форму одно изображение. Класс Image дает возможность загрузить изображение на экран телефона, это может быть фон дисплея, элемент интерфейса; Q int append (Item item) - этот метод добавляет любой из доступных компонентов класса Item в созданную форму; Q int append (String s t r ) -добавляет в форму строку текста; Q void delete (int itemNum) - удаляет компонент, ссылающийся на параметр itemNum; Q void deleteAll ( ) - удаляет все компоненты из имеющейся формы; Q Item get (int itemNum) - получает позицию выбранного компонента; Q int getHeight ( ) ' - возвращает высоту экрана в пикселях доступную для встраиваемых компонентов;
Класс Form а int getwidth ( ) - возвращает ширину экрана в пикселях доступную . для встраиваемых компонентов; Q void insert (int itemNum, Item item) — вставляет компонент в форму до определенного компонента; Q void set (int itemNum, Item item) - устанавливает компонент, ссылающийся на компонент itemNum, заменяя при этом предшествующий компонент; Q void setltemStateListener (ItemStateListener iListener) устанавливает nepeMeHHyro.iListener для формы, заменяя при этом предыдущую переменную iListener; Q int size () - получает количество компонентов в форме. Благодаря вышеперечисленным методам все компоненты находящиеся в форме, могут быть отредактированы надлежащим образом, например: Form my form = new Form ( "Пример" ) ; myform. append (iteml) ; myform. append (item2); В этом примере в созданную пустую форму добавляются два объекта. Оба объекта, разумеется, должны быть созданы в коде. Точно так же можно воспользоваться всеми методами класса Form для редактирования создаваемой формы. Добавленные в форму компоненты организованны в виде колонок и обычно располагаются по ширине всего экрана. На рис. 6.1 изображен эмулятор с несколькими компонентами интерфейса. Все компоненты, встроенные в форму, жестко закреплены и не перемещаются. Редактировать компоненты можно при помощи методов класса Form, причем присоединенные компоненты располагаются друг под другом, выравниваясь горизонтально. Пользователь может перемещаться по компонентам формы с помощью клавиш Вверх и Вниз. Когда количество добавленных компонентов больше видимой части экрана телефона, то автоматически создается прокрутка. Внизу или вверху экрана появляется стрелочка, сигнализирующая об имеющихся компонентах, выпадающих из зоны видимости. При переходе в нижнюю часть экрана, как только верхний компонент выйдет из зоны видимости, стрелочка автоматически развернется на 180°, указывая в направлении новых компонентов, выпадающих из зоны видимости. Такой механизм реализован в любом телефоне вне зависимости от производителя. Можно добавлять любое количество компонентов в форму, но очевидно, что необходимо задуматься и о дизайне пользовательского инРис. 6.1. Расположение элементов в форме
. Классы пользовательского интерфейса терфейса и не валить все «в кучу». Наилучшим решением будет продуманная структура переходов с экрана на экран.
6.2. Класс Item Абстрактный суперкласс Item имеет иерархию из восьми подклассов. Каждый подкласс представляет один из элементов пользовательского интерфейса, например, класс Text Field, создает текстовые поля для ввода пароля, адреса электронной почты или просто числовых значений. Все восемь классов, по сути, устанавливают компоненты пользовательского интерфейса, которые встраиваются в форму определенную классом Form. На рис 6.2 изображена иерархия абстрактного суперкласса Item.
Рис. 6.2. Иерархия суперкласса Item G ChoiceGroup - это группа связанных элементов для дальнейшего выбо. ра предполагаемых действий; О Customltem - с помощью этого класса можно добавлять различные графические элементы в форму; ID DateField - класс, с помощью которого имеется возможность редактировать время и дату; О Gauge - допускает графическое отображение диаграмм, процессов загрузки; Q Imageltem - осуществляет показ изображения на экране телефона; Ul Spacer — задает определенное по размеру пространство; Q Stringltem- с помощью этого класса можно создать произвольный текст. Этот класс не допускает редактирования, он лишь отображает информацию; G TextField - предоставляет текстовые поля для редакции. Любой из рассмотренных классов наследуется из суперкласса Item и может быть добавлен на экран, созданный классом Form. Каждый компонент класса Item содержит с левой стороны область, где при желании можно отобразить
Класс Item изображение в виде иконки. При перемещении компонента, иконка также перемещается вместе с компонентом. Класс Item с помощью имеющихся в его составе директив задает, в основном, формат отображения для любого компонента. Формат определяет заданную ширину, высоту или выравнивание компонентов в форме, а также класс Item имеет множество методов осуществляющих контроль над компонентами.
Методы класса Item Q void addCommand (Command cmd) - добавляет команду.к компоненту; Q String getLabeK) - получает метку объекта Item; Q int getLayout ()'- использует следующие директивы для размещения компонентов в форме: Q LAYOUT_LEFT - выравнивание по левой стороне; О LAYOUT_RIGHT - выравнивание по правой стороне; Q LAYOUT_CENTER - выравнивание по центру; О LAYOUT_TOP - выравнивание к верхней области формы; О LAYOUT_BOTTOM - выравнивание по нижней стороне экрана; Q LAYOUT_VCENTER - вертикальное выравнивание по центру. Горизонтальная и вертикальная директивы могут комбинироваться при помощи оператора «|». О int getMinimumHeight ( j -получает минимальную высоту для компонента; Q int getMinimumWidth() - получает минимальную ширину для компонента; Q int getPref erredHeight ( ) - получает предпочтительную высоту компонента; О int getPreferredWidth() - получает предпочтительную ширину компонента; Q void .notifyStateChanged() - компонент, содержащийся в форме. Уведомляет объект ItemStateListener о своем состоянии; Q void removeCommand(Command cmd) - удаляет команду из компонента; Q void setDefaultCommand (Command cmd) - встроенная команда по умолчанию для данного компонента; Q void setltemCommandListener(ItemCommandListener 1)-устанавливает обработку событий для компонента; Q void setLabel (String label) - устанавливает назначенную метку для компонента; Q void setLayout (int layout) - устанавливает директивы для форматирования компонента; Q void setPreferredSize(int width, int height) -устанавливает оптимальную высоту и ширину компонента. . При использовании вышеперечисленных методов можно настраивать и редактировать компоненты класса Item. В иерархии класса Item содержится'ряд
Ц
Классы пользовательского интерфейса
подклассов, обеспечивающих создание интуитивно понятного пользовательского интерфейса. Давайте рассмотрим эти подклассы.
6.2.1. Класс ChoiceGroup С помощью класса ChoiceGroup можно встраивать в форму группу элементов. Группы элементов делятся на три типа: эксклюзивный (EXCLUSIVE), множественный (MULTIPLE) и всплывающий (POPUP). Посмотрите на рис 6.3, где показан эмулятор мобильного телефона, показывающий все три группы элементов. Первый тип группы элементов на рис 6.3, выполнен в виде выпадающего меню и спрограммирован на основе типа POPUP. В данном случае это список из четырех флажков, с помощью которых можно выбрать заданные действия. Четыре флажка в меню были созданы абсолютно произвольно. Количество флажков и как следствие, количество вариантов выбора зависит от задачи поставленной перед программистом. Следующая группа, изображенная на рис. 6.3 представлена типом MULTIPLE. В этой группе элементов пользователь имеет возможность многократного выбора, т.е. можно выбрать сразу несколько вариантов. Обычно такая группа элементов используется при настройке различных опций, где Рис 6.З. Типы возможно указать сразу несколько вариантов выбора. Третья группы и последняя группа элементов задается типом EXCLUSIVE, и элементов возможен лишь один вариант выбора заданного флажка. ЧтоChoiceGroup бы создать в приложении необходимую группу элементов нужно воспользоваться конструктором класса ChoiceGroup. Всего имеется два конструктора. Первый конструктор с двумя параметрами: public ChoiceGroup(String label,int choiceType) Параметры конструктора ChoiceGroup: О label - это строка текста или информационная метка; Q choiceType - тип, указывающий на создаваемую группу элементов. Его можно задавать, например, следующим образом: Choice.EXCLUSIVE, Choice.MULTIPLE или Choice.POPUP. И второй конструктор с четырьмя параметрами, дающий программисту более интересный выбор в использовании графических изображений: public ChoiceGroup(String label, int choiceType, String[] stringElements, Image[] imageElements)
Класс Item Параметры конструктора ChoiceGroup: Q String - строка текста; Q choiceType - тип, указывающий на создаваемую группу элементов; Q str ingElement s - заданный массив текста для каждого элемента группы; Q imageElements - заданный массив изображений для каждого элемента группы. Два последних параметра конструктора класса ChoiceGroup предназначены для создания массива названий и изображений для элементов группы, например, таким образом: String[] string = {"Флаг 0 " , " Ф л а г 1","Флаг 2 " , " Ф л а г 3 " } Для того чтобы добавить в пустую форму класса Form все три имеющиеся группы элементов, нужно создать три объекта класса ChoiceGroup и воспользоваться методом append ( ) класса Form, например: ChoiceGroup groupMultiple = new ChoiceGroup("Группа Multiple", ChoiceGroup.MULTIPLE); ChoiceGroup groupPopup = new ChoiceGroup("Группа Popup",ChoiceGroup.POPUP); ChoiceGroup groupExclusive = new 'ChoiсeGroup("Группа Exclusive", ChoiceGroup.EXCLUSIVE); Form myform = new Form("Встроенный ChoiceGroup"); myform.append(groupPopup); myform.append(groupMultiple); myform.append(groupExclusive); Большой пользы простое статическое отображение элементов группы на дисплее телефона принести не может. Поэтому необходимо познакомится с методами класса ChoiceGroup, с помощью которых можно удалять, добавлять и отслеживать состояние каждого элемента группы.
Методы класса ChoiceGroup Всего имеется семнадцать методов, ознакомимся с основными и наиболее используемыми методами. О int append (String stringPart,Image imagePart) -добавляет элемент в группу; Q void delete (int elementNum) -удаляет заданный элемент из группы; Q void deleteAHO - удаляет все элементы; Q Font getFont(int elementNum) - получает используемый шрифт элемента группы; Q Image getlmage(int elementNum) - получает изображение для элемента группы; Q int getSelectedFlags(boolean[]selectedArray_return) -возвращает значение Boolean для группы элементов. Обычно эта функция используется с эксклюзивным типом элементов группы;
I
Классы пользовательского интерфейса
Q int getselectedlndex()- возвращает индекс выбранного элемента группы; U void insert (int e^mentNum, String stringPart,Image imagePart) - вставляет элемент в группу; U boolean isSelectedt int elementNum) - получает выбранную логическую величину. О void set(int elementNum, String stringPart, Image imagePart) - устанавливает текст и изображения в заданный элемент группы, при этом удаляя предыдущую запись; •Q void setFont(int elementNum, Font font) - устанавливает шрифт заданному элементу; Q void setSelectedlndex(int elementNum, boolean selected) устанавливает особое состояние для элемента группы при использовании множественного типа; Q int s i z e ( ) - возвращает количество используемых элементов группы. Прежде чем рассматривать практическую часть раздела, давайте разберемся, что именно от нас требуется чтобы воспользоваться компонентами класса ChoiceGroup. Итак, сначала необходимо создать объ,ект класса Form или пустую форму, куда можно встроить объекты класса Choi ceGroup. Далее необходимо определить, что именно будет происходить при выборе элемента группы. Я предлагаю рассмотреть вариант перехода в новое окно после выбора конкретного элемента группы, Где мы выведем простую информационную надпись. Для этого необходимо создать две команды перехода. Одна из команд будет реагировать на выбранный элемент группы, перемещая пользователя в новое окно, а другая команда перехода - возвращать в окно выбора. Пожалуй, это все что от нас сейчас требуется, поэтому давайте перейдем к реализации этого примера. Предлагаю не рассматривать по отдельности каждый кусок кода всей программы, а проанализировать весь пример целиком, поле чего остановиться на наиболее непонятных местах программного кода. В листинге 6.1 показан исходный код рассматриваемого примера, который находится на компакт-диске в папке \Code\Listing6_l\src. /**
Листинг 6.1 Класс ChoiceGroup */ import javax.microedition.midlet.*; import javax.microedition.Icdui.*; public class MainClassChoiceGroup extends MIDlet implements CommandListener { // команда выхода из приложения
Класс Item private Command exitMidlet = new Command (" Выход ", Command . EXIT , 0 ) ; // команда выбора элемента группы private Command vibor '= new Command (" Выбрать ", Command . SCREEN , 1) ; // команда возврата в главное окно private Command vozvrat = new Command ( "Назад" , Command . BACK , 0) ; // объект класса ChoiceGroup private ChoiceGroup groupPopup; // объект класса Form private Form my form, • // объект mydisplay представляет- экран телефона private Display mydisplay; public MainClassChoiceGroupf){ mydisplay = Display .getDisplay( this) ; } // текст для элементов группы private String [] mygroup = {"Флаг б", "Флаг 1","Флаг 2", " Флаг 3 " } ; public void startAppO { // инициализируем объект groupPopup groupPopup = new ChoiceGroup ( "Группа Popup", ChoiceGroup . POPUP , mygroup , null ) ; // создаем форму при помощи объекта Form myform =. new Form(« Встроенный ChoiceGroup «) ; // добавляем группу элементов my form. append (groupPopup) ; my form.addCommand( exitMidlet) ; myform. addCommand (vibor) ; myform. setCommandListener (this) ; •// отражаем текущий дисплей mydisplay .setCurrent (myform) ; public void ,pauseApp( ) {} public void destroyAppf boo lean unconditional) {} public void commandAction (Command c, Displayable d)
.
Классы пользовательского интерфейса // выход из приложения if(с == exitMidlet) { destroyApp(false); notifyDestroyed(); } // возврат в myform if(с == vozvrat) { mydisplay.setCurrent(myform); } // обработка выбранного элемента в группе if(с == vibor)
(
int i = groupPopup.getSelectedlndex(); if(i == 0) { Form formPopup = new Form("Это formPopup"+ mygroup[0]); formPopup.append(mygroup[ 0 ] ) ; formPopup.addCommand(vozyrat); formPopup.addCommand(exitMidlet); formPopup.setcommandListener(this); mydisplay.setCurrent(formPopup); } if(i == 1) {• Form formPopup = new Form("Это formPopup"+ mygroup[1]); formPopup.addCommand(vozvrat); forraPopup.append(mygroup[1]); -formPopup.addCommand(exitMidlet); formPopup.setcommandListener(this); mydisplay.setCurrent(formPopup); } if(i == 2) { Form .formPopup = new Рогт("Это, formPopup" + mygroup[2]); formPopup.append(mygroup[2]); • formPopup.addCommand(vozvrat); formPopup.addCommand(exitMidlet); formPopup.setCommandListener(this.) ; mydisplay.setCurrent(formPopup);
Класс Item if(i == 3) { Form formPopup = new Form ("Это formPopup"+ mygroup [ 3 ] ) ; formPopup. append (mygroup [3 ] ) ; formPopup. addCommand(vozvrat) ; formPopup . addCommand (exitMidlet ) ; formPopup. setCommandListener (this) ; mydisplay .setCurrent (formPopup) ;
Вся программа основывается на классе MainClassChoiceGrop. К команде выхода exitMidlet добавлены еще две команды обработки событий - это vozvrat и vibor. Команда vozvrat возвращает пользователя обратно в главное окно приложения, в которое он попадает при запуске программы. С помощью команды vibor, происходит выбор заданных действий, то есть отклик программы на выбранный элемент группы. Как мы уже договорились, каждый элемент группы POPUP (всего их будет четыре), должен привести пользователя в свой экран, установленный с помощью класса Form. Далее в листинге 6.1 идет объявление необходимых объектов для классов Form, ChoiceGrop и Display. После конструктора идет строка кода создающая текст для элементов группы: private String[] mygroup = {"Флаг 0 " , "Флаг 1","Флаг 2 " , "Флаг 3 " } ; С помощью переменной mygroup создается массив текстовых данных для инициализации всей группы элементов. После создания, переменной mygroup следует код метода startApp ( ) . Первой строкой кода в методе startApp ( ) инициализируется объект groupPopup класса ChoiceGroup. Конструктор этого класса мы подробно уже рассматривали, но небольших пояснений требуют два последних параметра. Оба параметра могут быть представлены в виде массива данных. Предпоследний параметр конструктора класса ChoiceGroup, инициализирующий объект mygroup, создает четыре строки текста в виде выпадающего меню (поскольку мы использовали значение POPUP во втором параметре конструктора класса ChoiceGroup). Все четыре строки текста и есть группа, элементов, дающая пользователю выбор конкретных действий. Последний параметр в конструкторе класса ChoiceGroup служит для загрузки каждому элементу группы своего изображения или иконки, которая будет отображаться слева от текста, назначенного для каждого элемента группы. Поскольку изображения вы еще загружать не умеете (чему мы, безусловно, научимся), то надо выставить это значение в null. После инициализации объекта groupPopup создается форма
EEElfliBIHIIIII
Классы пользовательского интерфейса
на основе класса Form, добавляются команды выхода и выбора, и самое главное, происходит встраивание объекта groupPopup класса ChoiceGroup в форму класса Form. После чего текущий экран дисплея отображается посредством строки кода: mydisplay.setCurrent(myform); Последующие действия всей программы сводятся к обработке событий возникающих при нажатии клавиш телефона. Если посмотреть на эту программу на экране телефона, то мы увидим на дисплее строку текста и выпадающее меню с четырьмя элементами. Выбрав один элемент из группы с помощью кнопки Select, на правой клавише телефона мы получим команду Выбрать, благодаря которой можно будет перейти в новое окно, заданное для выбранного элемента группы. После того, как произведен выбор элемента группы и нажата клавиша с командой Выбор, программа попадает в обработчик событий этой команды, назначенный дляшеременной vibor. Далее используется метод getSelectedlndexO класса ChoiceGroup, с помощью которого происходит получение индекса выбранного элемента группы и помещение результата в переменную i. После чего происходит сравнение полученного индекса с четырьмя значениями, заданными для каждого элемента. Соответственно, после совпадения индекса и значения выбранного элемента, происходят действия заданные для этого выбора. В примере происходит создание нового экрана с информационной надписью о выбранном элементе группы, добавлением команд выхода из приложения и возврата в главное окно программы. В этой программе, в ответ на действия по выбору элемента группы, создается новый экран с объектом класса Form. В ваших программах это могут быть любые другие события, необходимые для решения конкретных задач.
6.2.2. Класс DateField Это, пожалуй, самый простой класс из всех имеющихся в иерархии класса Item. С помощью класса DateField возможно произвести установку необходимой даты и времени. Используемый интерфейс для отображения даты и времени элементарный и практически все действия по установке заданных параметров даты и времени уже реализованы программно. На рис. 6.4 изображен эмулятор телефона, отображающий текущее время. В составе класса DateField имеется в наличии два конструктора, для создания объектов этого класса, рассмотрим их. Первый конструктор: public DateField(String label, int mode); Параметры конструктора класса DateField: Q label - строка текста; D mode - с помощью этого параметра конструктора, устанавливается, какой именно из компонентов класса DateField будет воссоздан на экране. Имеется возможность вывести дату с помощью значения DATE, и время,
Item Рис 6.4. Текущее время на экране телефона задав значение TIME. Также можно пользоваться комбинированным способом DATEJTIME для отображения обоих компонентов вместе. Второй конструктор содержит добавочный параметр и позволяет устанавливать время по часовому поясу. public DateField(String label, int mode, TimeZone timeZone) Параметры конструктора клacca Da t e F i e 1 d: Q label-строкатекста; Q mode - установка заданных компонентов класса DateField; Q timeZone- это объект класса TimeZone, С помощью которого можно определить часовой пояс. Например: TimeZone v = TimeZone.getTimeZonet"GMT"); Класс DateField содержит всего четыре метода: , Q Date getDate ( ) - возвращает текущую дату; О void setDate(Date date) - устанавливает новую дату; Q int get!nputMode() - получает'установленные компоненты DATE, TIME ИЛИ DATA_TIME; Q void setlnputMode (int mode) - устанавливает компоненты DATE, TIME ИЛИ DATEJTIME. Перейдем к программному коду и рассмотрим пример, реализующий вывод на экран даты и времени одновременно. Все, что сейчас от нас требуется - это написание кода основного класса мидлета, создание пустой формы и встраивание в эту форму класса DateField. Также необходимо проследить наличие команды выхода из приложения. Все остальное за нас сделает Java 2 ME, создав кнопки перехода и команду сохранения настроек даты и времени. В листинге 6.2 дается полный код примера к этому разделу, на компакт-диске исходный код на-' ходится в папке \Code\Listing6_2\src.;
'/** Листинг 6 . 2 Класс DateField */
- .
import javax.microedition.midlet.*; import javax.microedition.Icdui.*;
,
Классы пользовательского интерфейса public class MainClassDateField extends MIDlet implements CommandListener < // команда выхода из приложения private Command exitMidlet = new Command ( «Выход» , Command . EXIT , 0 ) ; // объект класса DateField private DateField dt; // объект класса Form private Form my form, • // объект mydisplay представляет экран телефона private Display mydisplay;
public MainClassDateField () { mydisplay = Display .getDisplay( this) ; public void startAppO { // инициализируем объект dt dt = new DateField ( "Дата и Время", DateField. DATE_TIME ) // создаем форму при помощи объекта Form myform = new Form ( "Встроенный DateField"); // добавить объект dt my form, append (dt ) ; my f orm.addCommand ( exitMidlet ); myform. set CommandListener (this) ; // отразить текущий дисплей mydisplay . setCurrent (myform) ; public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable d) * i // выход из приложения if(с == exitMidlet) destroyApp(false); notifyDestroyed(); } }
ШММИШ
Класс Item
В примере создан класс MainClassDateField, соответствующий названию разбираемого класса. Сам по себе пример очень легкий в силу простоты реализации самого класса DateField. Первоначально создается объект dt для класса DateField, после этого происходит его инициализация.в методе startApp ( ) . Создается форма классом Form и объект dt интегрируется в эту форму. Все остальное, а именно: циферблат и календарь, показанные на рис. 6.4, создаются автоматически с помощью эмулятора телефона при выборе одного из элементов класса. В нашем примере был создан объект dt класса DateField, но можно было этого и не делать, а обойтись, например такой простой записью: Form f = new Form(new D a t e F i e l d ( " Д а т а и Время", DateField.DATE_TIME); *\\ Такая запись используется иногда в профессиональных программах, где это действительно очевидно и не затруднит чтения и понимания всей программы в целом. После того, как вы откомпилируете этот пример и запустите приложение, на экране появятся два элемента с надписями time и date. Выбрав один из элементов и нажав на кнопку Select, вы попадете, в зависимости от выбора, на экран с календарем или временем, изображенным на рис. 6.4. С помощью джойстика или клавиш перемещения, можно установить необходимые параметры для обоих элементов.
6.2.3. Класс TextField С помощью этого класса можно создать заданный по размеру контейнер, в который помещается редактируемый текст. Этот класс обычно используется в создании адресных книг или полей для ввода текста. Кроме текста также можно размещать любую числовую информацию. В классе TextField существует всего один конструктор с четырьмя параметрами, рассмотрим этот конструктор. public TextField(String label, String text, irit maxSize, int constraints)
V
Параметры конструктора класса TextField: О label - метка, название для редактируемого поля; О text - строка текста. Поле может и не содержать текст; Q maxSize - максимальное количество символов в поле; Q constraints — входное ограничение, с помощью которого можно задавать, что именно должно принимать данное поле, например цифры, буквы или символы, задается ограничение с помощью следующих констант: Q static int ANY - можно вводить любой текст; Q static int DECIMAL - можно вводить дробные числа; Q static int EMAILADDR - используется для адреса электронной почты;
'
EE3HHIHHIIII8
Классы пользовательского интерфейса
О static int NUMERIC-для ввода только целого числа; Q static int PASSWORD - используется при вводе пароля; О static int PHONENUMBER - для ввода телефонного номера; О static int URL - адрес сайта в Интернет. Как видите, предусмотрены практически все варианты, остается только подставлять требуемые значения и наслаждаться простотой программирования под Java 2 ME. Использование вышеперечисленных директив в Java 2 ME традиционно и, например, для ввода адреса сайта может быть следующая запись: TextField t.f = new T e x t F i e l d ( " А д р е с " , " " , 2 0 , T e x t F i e l d . U R L ) ;
Методы класса TextField Класс TextField содержит четырнадцать методов, некоторые из них мы сейчас рассмотрим. Q void delete (int o f f s e t , int length) - удаляет текст или заданный символ; Q int getCaret Posit ion О --получает позицию каретки для печати символов; О int getChars (char [ ] data) - копирует текст в символьный массив данных; Q int g e t M a x S i z e f ) - определяет максимально доступное количество символов для размещения в классе TextField; О String getStringO - получает строку текста; , Q void insert(char[] data, int o f f s e t , int length, int position) - вставляет в заданную позицию массив символьных данных; Q void insert (String src, int position) - вставляет в заданную позицию строку текста; Q void setChars (char[ ] data, int o f f s e t , int length) -устанавливает из символьного массива данные в заданную позицию, при этом заменяя предыдущие данные; О int size ()-определяет размер содержимого в TextField на данный момент. Теперь перейдем непосредственно к примеру, реализующему возможности класса TextField. Создадим пустую форму, и вставим в нее поля в виде адресной книги. В листинге 6.3 дается код всего примера.
/** Листинг 6.3 Класс TextField */ import javax.microedition.midlet.*; import javax.microedition.Icdui.*; public class
MainClassTextField extends MIDlet
Класс Item . implements CommandListener { // команда выхода из приложения private Command exitMidlet = new Command ( " Выход " , Command . EXIT , 0 } ; // объект класса Form •private Form myform; // объект mydisplay представляет экран телефона' private Display mydisplay; 'public MainClassTextField( ) { mydisplay = Display .getDisplay( this) ; } public void startAppO {" // создаем форму при помощи объекта Form myform = new Form( "Класс TextField"); // добавить в форму поле для текста my form. append (new TextField( "Введите текст: " ,." " ,20 .TextField. ANY) ) ; // добавить в форму поле для пароля my form. append (new TextField ( "Введите пароль: '* , " " ,20 , TextField. PASSWORD) ) ; // добавить в форму поле для e-mail my form. append (new TextField ( "Введите E-mail : " , " " ,20 , TextField. EMAILADDR) ) ; / / добавить в форму поле для URL . my form. append (new TextField ( "Введите URL: " , " " ,20 , TextField. URL) ) ; // добавить в форму поле для телефонного номера my form. append (new TextField ( "Телефонный номер: " , " " , 20 .TextField. PHONENUMBER) ) ; my form.addCommand( exitMidlet ) ; myform.setCommandListerier (this) ;. mydisplay .setCurrent (myform) ; , public void pauseAppO {} public void destroy App (boolean unconditional)^} public void commandAction (Command c, Displayabl.e d)
Классы пользовательского интерфейса // выход из приложения if(с == exitMidlet) destroyApp(false); notifyDestroyedt); } }
Пример представляющий возможности класса TextField так же находится на компакт-диске в папке \Code\ Listing6_3\src. В листинге 6.3 создается пустая форма при помощи класса Form и вставляется несколько текстовых контейнеров для пароля, адреса электронной почты, веб-сайта и любой другой комбинации символов и цифр. Возьмем для наглядности первую строку кода, создающую текстовое поле для размещения символов и цифр: myform.append(new TextField ("Введите т е к с т : " , " " , 2 0 , T e x t F i e l d . A N Y ) ) ; Здесь используется упрощенная запись без создания объекта класса TextField. Первый параметр конструктора TextField задает информационную строку текста - метку, поясняющую назначение данного текстового поляг В следующий параметр конструктора класса TextField, а точнее в переменную, отвечающую за текстовый массив данных, пользователь будет вводить необходимую информацию. Значение этого параметра пустое, но возможно поместить любой текст, который в последствии можно редактировать. Числовое значение 20 задает длину или количество введенных символов. Последний параметр использует константу ANY, дающую возможность вводить любую комбинацию символов и цифр. . Все созданные поля в листинге 6.3 используют рассмотренную выше конструкцию программного кода и только в последнем параметре конструктора TextField, значение варьируется для пароля, e-mail, веб-сайта и телефонного номера. Задавая различные значения последнему параметру при создании объекта этого класса, вы можете создать набор необходимых полей. На рис. 6.5 изображен эмулятор, показывающий несколько полей класса TextField.
6.2.4. Класс Stringltem Рассматриваемый класс позволяет интегрировать в форму строку текста, состоящую из двух частей - метки и заданного текста. Строка текста, выводимая на экран, не может быть изменена или отредактирована - это статический Рис. 6.5. Поля класса TextField
Класс Item текст, жестко заданный в параметрах конструктора класса Stringltem при создании объекта этого класса. Имеется два конструктора класса Stringltem, разберем их устройство. public StringItem(String label,String text) : Параметры конструктора класса Stringltem: Q label - метка для строки текста; Q text - строка текста. Второй конструктор класса Stringltem имеет три параметра и позволяет выбирать способ отображения текстовой информации. public Stringltem(String label, String text, int appearanceMode)
|
Параметры конструктора Stringltem: Q label - метка для строки текста; Q text — строка текста; Q appearanceMode - этот параметр содержит большое количество предустановленных значений, используя которые вы сможете отформатировать текст,.например, поместив его в кнопку и создав при этом команду, реагирующую на нажатие данной кнопки. Значения, устанавливающие выше перечисленные действия содержаться в пакете javax.microedition.lcdui.Item, рассмотрим несколько из них. Q BUTTON - создает кнопку с текстом; Q HYPERLINK - создает гиперссылку; Q LAYOUT_BOTTOM - выравнивание к нижней части экрана; Q LAYOUT_CENTER - выравнивание по центру экрана; Q LAYOUT_TOP - выравнивание к верхней части экрана; Q LAYOUT_LEFT - выравнивание к левой части экрана; Q LAYOUT_RIGHT - выравнивание к правой части экрана. При создании примера к классу Stringltem обязательно воспользуемся некоторыми значениями для параметра appearanceMode в конструкторе класса Stringltem. Методы класса Stringltem G int get AppearanceMode ( ) - возвращает заданный способ отображения текста на экране; Q Font getFont ( ) - получает шрифт текста; Q String getText ( ) - получает текст для класса Stringltem; О void setFont(Font f o n t ) - устанавливает шрифт текста; Q void setPreferredSize(int width, int height) -задает ширину и высоту текста; Q void setText(String text) - устанавливает текст для класса Stringltem.
Классы пользовательского интерфейса Пример, который будет предложен для класса Stringltem, создаст форму при помощи класса Form и разместит в форме текст. Первая строка текста выполнена в виде простой статической надписи, вторая сделана как гиперссылка. Выделив эту строку текста и нажав кнопку на телефоне перейти, вы попадете на экран с новой формой. А последняя третья строка текста выполнена просто в виде кнопки. Рассмотрим листинг 6.4 иллюстрирующий работу данного примера. /**
Листинг 6.4 Класс Stringltem */ import javax.microedition.midlet.*; import javax.microedition.Icdui.*; public class MainClassStringltem extends MIDlet implements CommandListener, ItemCommandListener { // команда выхода из приложения private Command exitMidlet = new Command("Выход", Command.EXIT, 0); // команда перехода по нажатию кнопки private Command perexodButton = new Command("Дальше",Command.ITEM, 1); // команда перехода по гиперссылке private Command perexodHyperlink = new Command (" Перейти.", Command.ITEM, 1); // команда возврата в основное окно private Command vozvrat = new Command("Назад", Command.BACK, 1); // объект класса Form private Form myform; // объект mydisplay представляет экран телефона private Display mydisplay; \ public void startApp() { mydisplay = Display .getDisplayfthis-) ; myform = new Form("Класс Stringltem"); Stringltem si = new Stringltem("Метку", "Текст"); myform.append(si); // создать гиперссылку 'Stringltem s2 = new Stringltem("Гиперссылка", "www.dmk.ru",Item.HYPERLINK);
Класс Item s2 . setDefaultCommand (perexodHyperlink) ; s2 . setltemCommandListener (this) ; my form. append (s2 j ; // создать текст в "виде кнопки Stringltem s3 = new Stringltem( "Кнопка" , "Опции" , Item. BUTTON)-; s3 . setDef aultCommand (perexodButton) ; s3 . setltemCommandListener (this) ; my form. append (s3 ) ; myf orm. addCommand(exitMidlet ) ; my form. setCoiranandListener (this) ; mydisplay . setCurrent (myf orm) ; ,
protected void destroyApp (boolean unconditional) {} protected void pauseAppO О // обработчик класса ItemCommandListener public void commandAct ion (Command c, Item i) { // переход в окно опций if (с == perexodButton) { Form fl = new Form ( "Опции" ); f 1 . append ( " Необходимые Опции" ) ; fl.addCommand(exitMidlet-) >• f 1 . addCommand (vozvrat ) ; f 1 . setCommandListener (this) ; mydisplay .setCurrent (f 1) ; } // переход по гиперссылке if (c == perexodHyperlink) {' Form f2 = new Form ( "Издательство ДМК" ) ; f 2 .append( "Сайт издательства ДМК"); f 2 . addCommand ( exitMidlet ) ; f 2 . addCommand (vozvrat ); f 2. setCommandListener (this) ; mydisplay. setCurrent (f 2 ) ;
public void commandAct ion (Command c, Displayable d)
Классы пользовательского интерфейса // выход из приложения i f (с == exitMidlet) { destroyApp ( f a l s e ) ; notifyDestroyed( ) ; // возврат в основную форму if (с == vozvrat) mydisplay . setCurrent (myf orm) ;
В коде листинга 6.4 для наглядности не использовался конструктор основного класса мидлета MainClassStringlt em, но добавлялся, как уже упоминалось новый интерфейс ItemCommandListener для установки обработки команд перехода в приложении. В методе startApp ( ) происходит создание пустой формы для класса Form и интеграция класса Stringltem. В строке кода: Stringltem si = new Stringltem ( "Метку" , " Т е к с т " ) ; Создается простой статический текст и выводится на дисплей телефона. Следующий блок кода: Stringltem s2 = new Stringltem ( "Гиперссылка" , "www.dmk.ru" , Item. HYPERLINK) ; s2 . setDef aultCommand (perexodHyperlink) ; s2 . setltemCommandListener ( t h i s ) ; my form . append ( s2 ) ; Stringltem s3 = new Stringltem( "Кнопка" , "Опции"», I tern. BUTTON) ; s3 . setDef aultCommand (perexodButton) ; s3 .setltemCommandListener ( t h i s ) ; myf orm. append ( s3 ) ; формирует текст на экране телефона, назначив для него обработчик событий при помощи метода setltemCommandListenerQ. Можно получить текст в виде активной ссылки. При создании объекта s2 класса Stringltem использовался конструктор .с тремя параметрами. Последний параметр этого конструктора как раз и отвечает за вид создаваемой ссылки. Была создана гиперссылка с помощью константы HYPERLINK. Блоком кода с объектом s3 уже создавалась кнопка. Эта кнопка является так же простым статическим текстом, но оформленным в виде прямоугольной кнопки. Объекту s3 так же назначается обработчик событий методом setltemCommandListener ( ) , благодаря чему и получается активная ссылка. Выбрав ее можно перейти в нужное место в приложении. Теперь наша программа имеет два одноименных обработчика событий с разными параметрами, представленными двумя интерфейсами CommandListener и ItemCommandListener. Обработчик событий созданный при помощи метода commandAction (Command с, Item i ) , следит за двумя активными ссылками,
Класс Item Рис. 6.6. Элементы класса gtringitem выполненными в виде гиперссылки и кнопки. Выбрав одну из активных ссылок и воспользовавшись соответственной командой перехода perexodButton - для кнопки и реrexodHyperlink, вы попадете на экран с новой формой и информационной надписью. Оба новых экрана созданы классом Form, где так же имеются две команды: exitMidlet для выхода из приложения и vozvrat - для возврата в основное окно. Эти две команды обрабатываются своим методом commandAct ion (Command с, Displayable d) интерфейса CommandListener. Для того, чтобы создать активную ссылку, необходимо воспользоваться интерфейсом ItemCommandListener, реализовав метод commandAction ( } для обработки необходимых событий. Рис. 6.6 показывает экран эмулятора с несколькими элементами класса Stringltem.
6.2.5. Класс Spacer Класс Spacer подвигает элемент на экране телефона, создавая тем самым свободное пространство с указанными размерами. Именно за создание свободного пространства на экране отвечает класс Spacer. При создании объекта класса используется один конструктор с двумя параметрами, при помощи которых задается создаваемое пространство на экране. Конструктор класса Spacer выглядит следующим образом: public Spacer (int minWidth, int minHeight) ; , Параметры конструктора Spacer: G minWidth - ширина в пикселях; О minHeight - высота в пикселях. Класс Spacer имеет четыре метода, все они просты и не нуждаются в пояснениях, в приложении 2 находится справочник по платформе Java 2 ME, в котором вы сможете найти описание существующих методов класса Spacer. Чтобы показать работу класса Spacer, рассмотрим простой пример, где создается область в пятьдесят пикселей по ширине и ноль по высоте, благодаря чему элемент, размещенный в форме, сдвигается на указанное пространство вправо. В качестве элемента встроенного в форму используется класс Text Fie Id. В листинге 6.5 дается исходный код примера, который можно найти на компакт-диске в папке \Code\Listing6_5\src. Листинг 6 . 5 Класс Spacer
Классы пользовательского интерфейса
imporjt javax .microedition.midlet . * ; import javax .microedition. Icdui . * ; public class MainClassSpacer extends MIDlet implements CommandListener { / / команда выхода из приложения private Command exitMidlet = new Command ( "Выход" , Command. EXIT, 0) ; // объект класса DateField private Spacer sp,// объект класса Form private Form myform; // объект mydisplay представляет экран телефона private Display mydisplay; public MainClassSpacer ( ) { mydisplay = Display .getDisplay( this) ;
public void startAppO { / / , инициализируем объект sp sp = new Spacer (50 , 0 ); // создаем форму при помощи объекта Form myform = new Form( "Класс Spacer"); •// добавить объект sp myf orm. append (sp) ; myform. append (new Text.Field(" Метку" , "Текст" ,20 ,TextField.ANY) ) ; myf orm. addCommand( exitMidlet) ; myform. setCommandListener (this) ; // отразить текущий дисплей mydisplay . setCurrent (myform) ;
public void pauseApp ( ) {} public void. destroyApp (boolean unconditional) {} public void commandAct ion (Command c, Displayable d)
Класс Item Рис 6.7. Пространство созданное классом Spacer
'
/ / выход' из приложения if (с == exitMidlet) Ч destroy App ( f a l s e ) ; notifyDestroyed( ) ;
В листинге 6.5 создается рабочий класс MainClassSpacer и форма на основе класса Form. Объявляется объект sp для класса Spacer и инициализируется в методе startApp { ) . При инициализации объекта sp используются два значения для параметров, создавая тем самым пустое пространство с левой стороны от текстового поля, созданного при помощи класса TextField. Эмулятор изображенный на рис. 6.7 показывает работу программы из листинга 6.5. Класс Spacer был добавлен в Java 2 ME для профиля MIDP 2.0, нельзя сказать, что этот элемент жизненно необходим, но бывают случаи, когда использование класса Spacer облегчает работу программиста.
6.2.6. Класс Im ageItem С помощью класса Imageltem возможна загрузка изображения в форму представленную классом Form. Изображением может быть любая картинка формата PNG (Portable Network Graphics - формат портативной сетевой графики), выполненная в виде иконки, фотографии, заставки, фона и так и далее. Имеются два конструктора класса Imageltem. Первый конструктор содержит четыре параметра, рассмотрим этот конструктор: . * public Imageltem (String label, Image img , int layout , String altText) Параметры конструктора Imageltem: Q label - метка; О img - объект класса Image, содержащий изображение; Q layout - форматирует загружаемое изображение на экране телефона, с помощью использование следующих директив: Q public s t a t i c f i n a l int LAYOUT_DEFAULT - размещение изображения по умолчанию;
.
j
Классы пользовательского интерфейса
Q public s t a t i c f i n a l int LAYOUT_LEFT - размещение изображения со сдвигом к левой стороне экрана; Q public static f i n a l int LAYOUT_RIGHT - размещение изображения со сдвигом к правой стороне экрана; Q public s t a t i c f i n a l int LAYOUT_CENTER - размещение изображения со сдвигом к центру экрана. Q altText - информационный текст, используемый в замен загружаемого изображения. Если текст не используется — этот параметр нужно установить в значение null. 1 Второй конструктор класса Imageltem имеет на один параметр больше и выглядит следующим образом: public .Imageltem(String label, Image img, int layout, String altText int appearanceMode) Параметры конструктора Imageltem: Q label - метка; Q img — объект класса Image, содержащий изображение; Q layout - форматирование загружаемого изображения на экране телефона; D altText - текст, использующийся в замен загружаемого изображения; Q appearanceMode - этот параметр содержит ряд значений: О BUTTON - создает кнопку с текстом; Q HYPERLINK - создает гиперссылку; О LAYOUT_BOTTOM - выравнивание к нижней части экрана; Q LAYOUT_CENTER - выравнивание по центру экрана; Q LAYOUT_TOP - выравнивание к верхней части экрана; G LAYOUT_LEFT - выравнивание к левой части экрана; О LAYOUT_RIGHT - выравнивание к правой части экрана. С помощью этих значений можно создать активную ссылку и оформить изображение в виде кнопки или гиперссылки. В разделе 4.9 при рассмотрении класса Stringltem мы уже сталкивались с этими значениями, создавая статический текст в виде кнопки и гиперссылки. При загрузке изображений с помощью класса Imageltem существует ряд нюансов, на которые необходимо обратить внимание. Класс Imageltem является подклассом класса Image, прежде чем воспользоваться классом Imageltem, необходимо создать объект класса Image. Затем поместить или загрузить в объект класса Image изображение и только потом воспользоваться классом Imageltem для размещения изображения на экране представленного объектом класса Form. Создавая объект класса Imageltem, вы создаете своего рода контейнер для содержания ссылки на объект Image. Рассмотрим небольшой фрагмент кода, иллюстрирующий создание и загрузку изображения:
Класс Item
|
Image a = Image.'createlmage ( " / r i s . p n g " ) ; Imageltem b = new Imageltem("Рисунок", a, Imageltem.LAYOUT_CENTER,null); Первым делом создается объект i класса Image, после чего происходит загрузка необходимого Изображения посредством вызова метода createlmage ( ) класса Image. Далее создается объект im класса Imageltem, который будет содержать ссылку на объект image. Изображение, загружаемое в приложение, может находиться в любом месте рабочего каталога. При использовании, например J2ME Wireless Tollkit 2.1, изображение лучше поместить в папку \res. Эта папка по умолчанию для файлов ресурса к разрабатываемому приложению и в этом случае запись /ris.png будет обращаться к папке \res. Если вы хотите использовать другую папку, то необходимо указать весь путь при загрузке изображения, например: Image ikonl = I m a g e . c r e a t e l m a g e ( " / I k o n / L e v e l 2 / i k o n l . p n g " ) ; Рассмотрим пример загрузки изображения на экран в виде фона. В качестве изображения послужит фотография автора этой книги, которую мы загрузим и выведем на экран телефона. Код примера содержится в листинге 6.6 и папке \Code\Listing6_6\src на компакт-диске.
/** Листинг 6.6 Класс Imageltem */ import javax.microedition.midlet.*; import javax.microedition.Icdui.*; public class MainClassImageltem extends MIDlet implements CommandListener { // команда выхода из приложения private Command exitMidlet = new Command("Выход", Command.EXIT, 1); // объект класса Form private Form myform = new Form("Изображение"); // объект mydisplay представляет экран телефона private Display mydisplay; public MainClassImageltem() C mydisplay = Display.getDisplay(this);
Классы пользовательского интерфейса public void startApp() { // перехватываем исключительную ситуацию try{ // загрузка изображения Image image = Image. createlmage (" /gornakov.png" ); // создаем объект класса Itemlmage Imageltem im = new Imageltem( "Фотография" , image , Imageltem. LAYOUT_CENTER, " " ) ; // добавляем изображение в форму my form. append (im) ; } catch (Java . io . lOException ex) { } // установка обработчика событий для Form rnyform. addCommand (exitMidlet ) ; myf orm.. setCommandListener ( this ) ; / / отразить , текущий дисплей mydisplay .setCurrent (myf orm) ,-
public void pauseAppO {} public void destroy App (boolean unconditional) {} public void commandAction (Command c, Displayable d) { /У выход из приложения if (с == exitMidlet) Й* (1}Nokiai100SOK
destroyApp( false) ; notifyDestroyed( ) ;
Пример достаточно прост: происходит загрузка изображения на экран телефона представленного классом Forme добавлением команды выхода из приложения. Но после компиляции листинга 6.6 и запуска приложения на эмуляторе J2ME Wireless Toolkit 2.1, возникают цветовые дефекты в виде 'некачественного, отображения фотографии. Это вызвано, прежде всего, минимальной цветовой гаммой, представляемой эмулятором J2ME Wireless Toolkit 2.1. Протестируйте код из листинга 6.6 на различРис 6.8. Изображение, загруженное при помощи класса Imageltem
Класс Item
illil
ных эмуляторах, рассмотренных в главе 4. На рис 6.8 показан эмулятор с изображением на экране фотографии.
6.2.7. Класс Gauge С помощью класса Gauge создается графический измеритель различных процессов. То есть, возможно осуществить графическое отображение, например процесса загрузки файла, сохранения игры, поиска информации и т.д. Представление любого из процессов в графическом виде, дает возможность создать красивое интерактивное приложение. Визуальное отображение процесса осуществляется в виде заданного по размеру горизонтального столбца, который закрашивается слева направо по мере выполнения процесса. .К сожалению, определенного стандарта в графическом представлении, скажем того же столбца, не существует и каждый из производителей представляет свой разработанный вид графического контекста. На рис 6.9, изображен эмулятор телефона с графическим измерителем процесса. Класс Gauge имеет всего один конструктор, необходимый при создании объекта этого класса. Разберем конструктор класса Gauge: public Gauge(String label, boolean interactive, int maxValue, int initialValue) Параметры конструктора Gauge: Q label - метка или название процесса связанного с объектом Gauge; Q interactive - имеются два значения: true для интерактивного режима и false - для не интерактивного режима; Q maxValue - максимальное значение, задающее диапазон длительности всего процесса. Может быть установлено при помощи значения INDEFINITE; Q static int INDEFINITE - специальное значение, устанавливающее максимальную величину, при неизвестном диапазоне течения всего процесса; Q initialValue - параметр может быть инициализирован значением от нуля и до значения в параметре maxValue. Этим значением инициализируется начальный отсчет, от которого происходит увеличение визуального представления работы процесса. Кроме числовых значений возможно применение заданных констант: Q static int CONTINUOUS_IDLE - задает непрерывное циклическое течение процесса для не интерактивного режима при неопределенном диапазоне; Рис 6.9. Эмуляторы телефонов, показывающие использование класса Gauge
Классы пользовательского интерфейса О s t a t i c int CONTINUOUS_RUNNING-задает непрерывное бегущее течение процесса для не интерактивного режима при неопределенном диапазоне; • Q s t a t i c int INCREMENTAL_IDLE-задает пошаговое циклическое течение процесса для не интерактивного режима при неопределенном диапазоне; Q static int INCREMENTAL_UPDATING - задает пошаговое обновление течения процесса для не интерактивного режима при неопределенном диапазоне.
Методы класса Gauge Методы, имеющиеся в составе класса Gauge, позволяют настраивать графическое отображение течение процесса на экране телефона, рассмотрим некоторые из методов. О void addCommand (Command cmd) - добавляет команду; Q int getMaxValue ()—получает значение максимального диапазона работы процесса; Q int getValue ( ) - п о л у ч а е т текущее значение в процессе работы; Q void setltemCommandListener(ItemCommandListener 1)-устанавливает обработчик событий; Q void set Label (String label) - устанавливает метку для элемента; О void setLayout (int layout) — устанавливает директивы для элемента; Q void setMaxValue (int maxValue) - устанавливает максимальное значение течения процесса; О void setPreferredSize (int width, int height) -задаетширину и высоту для графического представления всего течения процесса; Q void s e t V a l u e f i n t value) — устанавливает текущее значение процесса. В примере создается простой измеритель течения процесса в виде прямоугольника, максимальный диапазон задан значением десять. В листинге 6.7 показано использование класса Gauge. Исходный код примера, также находится на компакт-диске в папке \Code\Listing6_7\src. / ** Листинг 6.7 Класс Gauge */ import javax.microedition.midlet. *,import javax.microedition.Icdui.*; public class MainClassGauge extends MIDlet implements CommandListener
Класс Item
§!!•
-// команда выхода из приложения private Command exitMidlet - new Command ( "Выход" , Command. EXIT, 1) ; // объект класса Form private Form myform = new Form( "Класс G a u g e " ) ; // объект mydisplay представляет экран телефона private Display mydisplay; public MainClassGauge ( ) { mydisplay = Display .getDisplay ( t h i s ) ; } public void startAppO { // добавить объект класса Gauge my form. append (new Gauge ( "Прогресс : " , true, 10, 5 ) ) ; // установка обработчика событий для Form my form.addCommandt exitMidlet) ; myform.setCommandListener (this) ; / / о т р а з и т ь текущий дисплей mydisplay . setCurrent (myform) ;
public void pauseAppO {} public void destroy App( boolean unconditional)
{}
public void commandAct ion (Command c, Displayable d) { // выход из приложения if (с == exitMidlet) { destroy App ( f a l s e ) ; notifyDestroyedO ;
Откомпилировав этот пример, вы увидите на экране прямоугольник, наполовину закрашенный темным цветом. Использование класса Gauge позволяет создавать экранные заставки отображающие, например, процесс загрузки приложения. Для того чтобы пользователь не наблюдал за черным экраном телефона в момент загрузки очередного процесса, создайте класс Gauge и используйте его по назначению.
Классы пользовательского интерфейса
6.3. Класс Alert Использование класса A l e r t в Java 2 ME приложениях обусловлено возник„новением различных внештатных ситуаций. В основном класс A l e r t применяется для создания экрана, который информирует пользователя об ошибке произошедшей в приложении или любом другом уведомлении информационного характера. Экран, определенный классом A l e r t может содержать строковое уведомление о произошедшей ошибке либо текстовую строку с заданным изображением. В связи с этим, класс Alert имеет два, конструктора, использующихся, в создании объектов этого класса. Первый конструктор содержит один параметр типа String, задавая строку текста для уведомления. Рассмотрим первый конструктор класса А1 е г t. public A l e r t ( S t r i n g t i t l e ) ; Параметры конструктора public Alert: Q t i t l e - строка текста. Второй конструктор класса Alert имеет уже четыре параметра, представляя более интересный вид создаваемого экрана. public A l e r t ( S t r i n g t i t l e , String alertText, image alertlmage, AlertType alertType) Параметры конструктора public Alert: Q title-название созданного экрана; Q alertText - текст уведомления; Q alertlmage - изображение; Q alertType - тип уведомления, определяемый классом AlertType. Существует пять типов уведомлений: Q static AlertType ALARM - тревога; О s t a t i c AlertType CONFIRMATION - предупреждение о возможном действии, которое пользователь должен произвести; Q s t a t i c AlertType ERROR - ошибка; Q s t a t i c AlertType INFO - информационное сообщение; Q s t a t i c AlertType WARNING - предупреждение. Создавая объект класса Alert, вы можете выбрать необходимый тип уведомлений или информационных сообщений, формируя органичные, удобные приложения, предусматривающие любые варианты развития событий.
6.3.1. Методы класса Alert Существует множество методов класса Alert, все они призваны создавать более насыщенные и информационные сообщения. Рассмотрим методы класса Alert.
Класс Alert Q void addCommand (Command cmd) - добавляет команду; Q int getDef aultTimeout ( ) - получает время для представления уведомления. Можно воспользоваться переменной FOREVER для постоянного представления экрана с объектом класса Alert; Q Image get Image () - получает изображение для экрана представленного классом Alert; Q Gauge getlndicator ( ) - этот метод позволяет воспользоваться графическим измерителем класса Gauge; Q String getStringO - получает текстовую строку; Q int getTimeout ( ) - получает заданное время для представления уведомления; Q AlertType getType ( ) - определяет тип используемого уведомления; Q void removeCommand (Command cmd) - удаляет команду; Q void setCommandListener (CommandListener 1) -устанавливает обработчик событий; О void setlmage (Image img) — устанавливает изображение; О void setlndicator (Gauge indicator) — устанавливает индикатор измерителя для использования класса Gauge; G void setString (String str) - устанавливает строку текста; Q void setTimeout (int time) - устанавливает время; Q void setType(AlertType type) - устанавливает тип уведомлений или информационных сообщений. Использовать возможности класса Alert в приложении необходимо. Уредомления об ошибках и различные информационные сообщения улучшают пользовательский интерфейс разрабатываемой программы. В листинге 6.8 приводится простой пример, иллюстрирующий создание и отображении класса Alert на экране телефона. Исходный код примера находится в папке \Code\Listing6_8\src.
/.** Листинг 6.8 Класс Alert */ import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class MainClassAlert extends MIDlet implements CommandListener { // команда выхода из приложения private Command exitMidlet = new Command("Выход", Command.EXIT, 1); // объект класса Alert
'
Классы пользовательского интерфейса Alert al; // объект mydisplay представляет экран телефона private Display mydisplay; / public MainClassAlert ( ) { mydisplay = Display .getDisplay (this) ; }, . public void startAppO { // перехватываем исключительную ситуацию try{ // загрузка изображения Image image = Image. createlmage (" /error .png" ); // объект класса Alert al = new Alert ( "Класс Alert", null, image, AlertType . ERROR) ; } catch ( Java. io.IQException ex) { } al .addCommand(exitMidlet) ; al .setCommandListener (this) ; mydisplay .setCurrent (al) ; public void pauseAppO {} public void destroyApp (boolean unconditional)
{}
public void commandAction (Command c, DisplayaMe d) { // выход из приложения if (с == exitMidlet) { destroyApp ( false) ; notifyDestroyed( ) ;
В листинге 6.8 создается класс MainClassAlert, являющийся основным классом мидлета. В самом начале всего кода происходит объявление необходимых переменных и в частности объекта al класса Alert. В методе startApp ( ) создается объект класса Image, в котором будет содержаться загружаемое изображение. Изображение выполнено в виде информационной надписи об ошибке и находится в папке \Code\Listing6_8\res на прилагаемом к книге компакт-диске. На рис. 6.10 изображена работа класса Alert.
Класс List
llllll
Рис 6.10. Информационное уведомление, созданное при помощи класса Alert При загрузке изображения используется конструкция try{} c a t c h ( ) { } для обработки исключительных ситуаций. В остальном, я думаю, весь код ясен и каких-либо проблем с пониманием этой простой программы возникнуть не должно.
6.4. Класс List Класс List не входит в иерархию класса Item. Использование класса List дает возможность создавать выбираемый список элементов, отображаемый на экране в виде одной или нескольких строк текста. Класс List наследуется от класса Screen и реализует возможности интерфейса Choice. При создании выбираемого списка элементов необходимо указать тип создаваемого списка. Существует всего три типа списков, реализация которых основана на использовании интерфейса Choice: Q EXCLUSIVE - предоставляет эксклюзивный выбор элемента в списке; Q MULTIPLE - множественный выбор элементов из списка; Q IMPLICIT - выбирает из списка только один элемент, на котором сфокусировал свое внимание пользователь. Конструкция применения типов EXCLUSIVE и MULTIPLE напоминает использование этих типов в классе ChoiceGroup, а вот применение типа IMPLICIT возможно только с использованием класса List. При создании объекта класса List можно воспользоваться двумя видами конструкторов. Рассмотрим их более подробно. public List(String title, int listType); Параметры конструктора List: О title - название создаваемого списка элементов; Q listType - тип создаваемого списка, может быть одним из трех значений: IMPLICIT, EXCLUSIVE И MULTIPLE. Этот конструктор с двумя параметрами создает пустой список с заданным типом в параметре listType. Второй конструктор класса List несколько сложнее. Он состоит из четырех параметров и создает многострочный список элементов с загрузкой иконки или изображения для каждого элемента. public List(String title, int listType, String[] stringElements, Image[] imageElements)
*
\
Классы пользовательского интерфейса
Параметры конструктора List: Q t i t l e - название создаваемого списка элементов; Q listType -может быть одним из трех значений IMPLICIT, EXCLUSIVE и MULTIPLE для определения типа создаваемого списка элементов; Q stringElements - в этом параметре используется массив строк для создания списка элементов; Q imageElements - с помощью этого параметра каждому из элементов можно загрузить свое изображение, чаще всего используются иконки маленьких размеров, например 10 на 10 пикселей.
6.4.1. Методы класса List Класс List имеет множество методов, с помощью которых можно производить редакцию списка элементов, выбор заданного элемента и многое другое. Разберем часть методов класса List. О int append(String stringPart, Image imagePart)-добавление списка элементов; О void delete (int elementNum) - удаление заданного элемента из списка; " Q void deleteAHO - удаление всех элементов; О Font getFont(int element-Mum) — получает шрифт для заданного элемента в списке; Q Image getlmagetint elementNum) - получает изображение для заданного элемента в списке; О int getSelectedFlags(boolean[] selectedArray_return) — возвращает состояние всех элементов в виде массива данных; Q int getSelectedlndex ( ) — получает выбранный индекс элемента в списке; Q String getString (int elementNum) - получает строку текста для выбранного элемента из списка; О void insert(int elementNum, String stringPart, Image imagePart) - вставляет элемент в список до указанного номера элемента в списке; Q boolean isSelected(int elementNum) - получает выбранный элемент из списка; Q void removeCommand (Command cmd) - удаляет команду для списка; Q void s e t ( i n t elementNum, String stringPart, Image imagePart) - вставляет новый элемент в список в замен предшествующего; Q void setFont(int elementNum, Font font) - устанавливает шрифт заданному элементу в списке; Q void setSelectCommand(Command command) — этот метод предназначен для работы с типом IMPLICIT. Когда используется такой тип списка, то выбирается элемент, на котором сфокусирована в данный момент
Класс List
UIHMEQ
строка состояния. Этот метод позволяет определить, на каком элементе сфокусировано внимание пользователя. При этом используется такая запись: List.SELECT_COMMAND. для определения выбранного элемента в списке; Q void setSelectedFlags(boolean[] selectedArray)-устанавливает состояние выбранных элементов; Q void setSelected!ndex(int .elementNum, boolean selected) устанавливает индекс выбранного элемента в списке; Q void setTitle (String s) - добавляет название в список элементов; Q int size ( ) - с помощью этого метода можно узнать количество элементов в списке. Теперь давайте создадим пример, описывающий основные возможности класса List. Класс List может создавать три списка элементов: Exclusive, Multiple и Implicit. Используем эту возможность и создадим код, реализующий все три типа. Основная идея создания примера для класса List сводится к следующему: при входе в приложение пользователь попадает в главное окно со списком из двух элементов Multiple и Implicit, а сам список этих двух элементов будет создан на основе типа Exclusive. Ко всем элементам списка будут загружаться свои иконки. Выбрав один из двух элементов списка курсором, пользователь должен нажать клавишу команды Выбор для перехода в программе. Оба элемента списка Multiple и Implicit будут представлять два разных типа списка. Выбрав один из элементов Multiple или Implicit, пользователь попадает на новый экран. Каждый из выбранных списков будет содержать ряд элементов иллюстрирующих работу типов Mu11 ipIe и Imp licit. Выбирая элементы из этих списков, пользователь будет получать информационное сообщение. В листинге 6.9 исходный код примера, а на компакт-диске исходный код размещается в папке \Code\Listing6_9\src..
/** Листинг б. 9 Класс List */ import javax.microedition.midlet.*; import javax.microedition.Icdui.*; public class MainClassList extends MIDlet implements CommandListener { // команда выхода из приложения private Command exitMidlet = new - Command("Выход", Command.EXIT, 0); // команда выбора элемента из списка private Command vibor = new Command("Выбор",
Классы пользовательского интерфейса Command. SCREEN, I); // команда возврата в главное окно private Command vozvrat = new Command ( "Назад" , Command . BACK , 1 ) ; // команда выбора элемента для типов Implicit и Multiple private Command OK = new Command( "OK" , Command. OK, 1); // массив иконок для типа EXCLUSIVE Image [] iconEx = null; // массив иконок для типа Multiple Image [] iconMu - null; // массив иконок для типа Implicit Image [] iconlm = null; // объект класса List для типа EXCLUSIVE private List mylistEx; // объект класса List для типа Multiple private List mylistMu; // объект класса List для типа Implicit private List mylistlm; // объект mydisplay представляет экран телефона private Display mydisplay; public MainClassList ( ) { mydisplay = Display. getDisplay (this) ;
public void startAppO { // перехватываем исключительную ситуацию try{ // загрузка изображения Image imagel = Image. createlmage ( "/iconMu. png" ); Image image2 = Image. createlmage {" /iconlm. png" ); //, поместить загруженные изображения в массив iconEx iconEx = new Image [] { imagel , image2 }; // загрузка изображения Image images = Image. createlmage (" /Multiple. png" ); //поместить загруженные изображения в массив iconMu iconMu = new Image [] (image3 , image3 , image3 , imageS } ; // загрузка изображения Image image4 = Image. createlmage (" /Implicit .png" ),-
Класс List // поместить загруженные изображения в массив iconlirt iconlm = new Image [] (image4, image4 , image4}; } catch (Java . io . lOException ex) { } // текст для двух элементов списка String [] st = ("Тип Multiple" , "Тип Implicit"};' // инициализация объекта mylistEx mylistEx = new List ("Тип EXCLUSIVE", .Choice. EXCLUSIVE, st , iconEx) ; // добавить команды mylistEx . addCommand (exitMidlet ) ; my 1'istEx, addCommand (vibor) ; mylistEx.setCommandListener (this) ; // отразить текущий дисплей mydisplay .setCurrent (mylistEx) ;
public void pauseAppO {} public void .destroy App (boolean unconditional) {} public void commandAct ion (Command c, Displayable d) { / / выход из приложения if (с == exitMidlet) { destroy App ( false) ;. , notifyDestroyed ( ) ; } // возврат в главное окно if (с == vozvrat) . Display .getDisplay( this) .setCurrent (mylistEx) ; // обработка команды OK if (с == OK) { Alert al = new Alert (null , "Информационное уведомление", null , null) ; mydisplay .setCurrent .(al) ; } // обработка команды vibor ' if (с == vibor) { // взять индекс выбранного элемента int i = mylistEx. getSelectedlndex (); // события для элемента «Тип Multiple» if(i == 0)
Классы пользовательского интерфейса // текст для элементов списка String [] string = { "Меч" , "Щит" , "Нож" , "Копье" }; // инициализация объекта mylistMu mylistMu = ' n e w List ("Тип MULTIPLE", Choice. MULTIPLE, string, iconMu); // добавить команду возврата mylistMu. addCommand(vozvrat) ; / / добавить команду OK mylistMu.addCommand (OK) ; mylistMu. setCommandListener (this) ; / / отразить текущий дисплей mydisplay . setCurrent (mylistMu) ; } // события для элемента «Тип Implicit» if(i == 1) { // текст для элементов списка String[] string = { "Звук'" , "Видео" , "Управление" }; // инициализация объекта mylistlm mylistlm = new ListC'Tnn IMPLICIT", Choice. IMPLICIT, string, iconlm) ; // добавить команду возврата mylistlm. addCommand (vozvrat) ; // добавить команду OK mylistlm. addCommand (OK) ; mylistlm. setCommandListener (this) ; // отразить текущий дисплей mydisplay. setCurrent (mylistlm) ;
В листинге 6.9 создан класс MainClassList, являющийся основным классом мидлета программы. В начале исходного кода создаются команды для выхода из приложения - exitMidlet, для выбора элемента из списка — vibor, для возврата в главное окно приложения - vozvrat и команда ОК, обрабатывающая выбранный элемент из группы. За командами обработки событий следует объявление трех переменных: iconEx, iconMu и iconlm. Все три переменные будут содержать массив изображений или иконок для трех рассматриваемых в этом примере типов Exclusive, Multiple и Implicit класса List. Затем в коде: private List mylistEx; private List mylistMu;
Класс List private List mylistlm,private Display mydisplay; Создаются три объекта класса List, представляющие три имеющихся типа элементов списка и объект mydisplay класса Display. Метод startAppO производит загрузку всех имеющихся .иконок из папки \Code\Listing6_9\res с помощью метода createlmage класса Image. Все загруженные иконки содержатся в^переменныхЛтаде!, image2, image3 и image4. При загрузке изображений используется конст§укция t r y { } catch ( ) {} для перехвата исключительной ситуации. Все иконки размещаются в массивах iconEx, iconMu и iconlm для каждого типа элементов списка. В сроке кода mylistEx = new List
'Тип EXCLUSIVE",
Choice.EXCLUSIVE, iconEx)
st,
происходит инициализация объекта mylistEx. Используется конструктор класса из четырех параметров. Первый параметр конструктора класса List создает заголовок для всего экрана. Во втором параметре конструктора используется значение Choice ^EXCLUSIVE. С помощью этого значения создается список элементов типа Exclusive, позволяющий выбрать только один элемент из всего списка. Третий параметр в конструкторе класса List принимает значение переменной st. Эта переменная содержит две строки текста, создавая тем самым только два элемента списка. Последний параметр загружает две иконки для обоих элементов списка. В методе commandAction ( ) происходит обработка всех имеющихся команд созданных в приложении. Команда exitMidlet производит выход из приложения. Команда vozvrat возвращает пользователя в главное окно программы. Команда ОК показывает информационное сообщение, выполненное на основе класса Alert. Команда vibor осуществляет переход в выбранный экран представленный списком элементов двух различных типов Multiple и Implicit класса List. С помощью метода getSelectedIndex() берется индекс выбранного элемента из списка и на его основе в конструкции if /else происходит обработка выбранных событий. Два типа списков Multiple и Implicit создаются подобно списку типа Exclusive. Рис. 6.11 изображает эмулятор, на экране которого воспроизводится список элементов организованный с помощью класса Li st. В мобильных приложениях очень часто используются различные списки элементов, поэтому необходимо изучить возможности класса List более внимательно. Рис. 6.11. Список элементов созданный классом List
Классы пользовательского интерфейса
6.5. Класс Ticker Объект класса Ticker служит для создания в приложении подобие бегущей строки, располагающейся в верхней части экрана. Текст, выводимый на экран объектом класса Ticker, перемещается справа налево с одинаковой скоростью. При достижении конца текста бегущая строка появляется заново, обеспечивая тем самым цикличность перемещения текста. На рис. 6.12 изображен эмулятор с бегущей строкой в верхней части экрана. Класс Ticker имеет один конструктор, необхвдимый в создании объекта этого класса, рассмотрим этот конструктор: public Ticker (String str)'; Параметры конструктора класса Ticker: Q str - строка текста появляющаяся в виде бегущей строки. Создавая объекта класса Ticker с помощью рассмотренного конструктора, вы задаете значение для параметра str и эта строка текста будет циклично прокручиваться в программе.
6.5.1. Методы класса Ticker В составе класса Ticker существует всего два метода для получения и установки необходимой строки текста для приложения. О String getstring ( ) - получает строку текста, заданную для объекта класса Ticker; О void setStr ing ('String str) - устанавливает строку текста для отображения ее на экране телефона с помощью объекта класса Ticker, заменяя ее новой строкой. Также имеется возможность воспользоваться еще двумя методами абстрактного класса Displayable. Оба метода выполняют аналогичные действия методам класса Ticker, но при этом позволяют встраивать объект класса Ticker непосредственно в форму, то есть экран представленный классом Form. Разберем эти два метода: Q void setTicker (Ticker ticker) -устанавливает новую бегущую строку, заменяя предыдущую; Q Ticker getTicker ( ) - получает используемую строку текста. Оба этих метода дублируют по сути методы класса Ticker. В листинге 6.10 приводиться образец применения класса Ticker, также весь исходный код находится на компакт-диске в папке \Code\Listing6_10\src. Рис. 6.12. Объект класса Ticker создает в верхней части экрана бегущую строку
Класс List
/** Листинг 6.10 Класс Ticker */ import javax.microedition.midlet . * ; import javax.microedition. Icdui . * ; public class MainClassTicker extends MIDlet implements CommandListener { / / команда выхода из приложения private Command exitMidlet = new Command! "Выход" , Command. EXIT, 0) ; // объект класса Form . .' private Form my form; // объект mydisplay представляет экран телефона private Display mydisplay; public MainClassTicker () { mydisplay = Display .getDisplayt this) ; } public void startApp ( ) { // создаем форму при помощи объекта Form myform = new Form( "Класс Ticker"); // создаем объект класса Ticker Ticker myticker = new Ticker ( "Бегущая строка"); // добавляем бегущую строку в форму myform. setTicker (my ticker) ; // добавить команду выхода my form.addCommand( exitMidlet ) ; myform. setCommandListener (this) ; mydisplay .setCurrent (myform) ;
public void pauseAppO {} public void destroy App (boolean unconditional) {} public void commandAct ion (Command c, Displayable d) { / / выход из приложения
Классы пользовательского интерфейса if (с == exitMidlet) { destroy App ( f a l s e ) ; notifyDestroyed ( ) ;
'В листинге 6.10 создается пустая форма с помощью класса Form и объект класса Ticker с заданным текстом. Методом setTicker ( ) , объект класса Ticker добавляется в форму, организовывая тем самым бегущую строку в верхней части экрана телефона.
6.6. Класс Image При рассмотрении класса Image It em мы уже использовали объекты класса Image, но тогда был рассмотрен только .один метод и способ работы с классом Image. В этом разделе вы более подробно познакомитесь с этим классом. Класс Image необходим для загрузки и хранения изображений в формате PNG. Чаще всего загружаемые изображения находятся в рабочем каталоге приложения. Но могут находиться и где угодно, надо только правильно указать путь местонахождения для загрузки. При упаковке приложения в JAR-файл, все имеющиеся изображения автоматически копируются в архив, и при работе программы на телефоне, загрузка уже осуществляется из JAR-файла. Загружаемые изображения могут использоваться во время работы с классами Alert, Choice, ChoiceGroup, Form, Imageltem и Graphics. Качество воспроизведения изображения на экраг не всецело зависит от возможностей используемого телефона. Если изображение больше фактического размера дисплея, то сервис телефона организует прокрутку изображения и если это не входит в ваши планы, то следует придерживаться минимальных размеров ширины и высоты при создании изображений.
6.6.1. Методы класса Image Все методы класса Image служат для загрузки изображений из файлов, ресурсов, потоков, а в некоторых методах можно задавать размеры и трансформацию изображений. Проанализируем основные методы класса Image. G static Image createlmage (byte ['] imageD.ata, int imageOffset, int imageLength) -загружает изображение учитывая смещение и длину- в байтах; • Q static Image createlmage (Image source) -загружает изображение из файла; О static Image createlmage(Image image, int x, int y, int width, int height, int transform) - загружает изображение в заданное место, определенное координатами, с возможностью трансформации изображения. Параметр transform устанавливает необходимую трансформацию с помощью класса Sprite и константных значений:
Класс Image Q Sprite, TRANS_NONE - изображение копируется без трансформации; Q Sprite.TRANS_ROT90 - трансформирует изображение по часовой стрелке на 90°; Q Sprite.TRANS_ROTl80- трансформирует изображение по часовой стрелке на 180°; Q Sprite.TRANS_ROT270 - трансформирует изображение по часовой стрелке на 270°; Q static Image createlmage (Inputstream stream) -загружает изображение из потока; ^ Q static Image createlmage{int width, int height) -загружает изображение в заданные размеры; Q static Image createlmage (String name) - загружает изображение из ресурса; Q static Image createRGBImage(int[]. rgb, int width, int height, boolean processAlpha) - загружает изображение, учитывая цветовую компоненту ARGB; Q Graphics getGraphics() — создает графический объект для представления изображения; О int getHeight ( ) - получает высоту изображения; Q int getwidth() - получает ширину изображения, В листинге 6.11 происходит загрузка изображения в приложение, но без использования объекта класса Image It em, который использовался при рассмотрении примера в листинге 6.6 из раздела 6.8. В листинге 6.6 применялась ссылка на объект класса Image, в этом примере объект класса Image используется напрямую. Исходный код примера можно найти на компакт-диске в папке \Code\Listing6_l l\src.
/** '
Листинг 6.11 Класс Image */
' \- .
import javax.microedition.midlet.*; import javax.microedition.Icdui.*; public class MainClassImage extends MIDlet implements CommandListener { // команда выхода из приложения private Command exitMidlet = new Command("Выход", Command.EXIT, 1); // объект класса Form private Form myform = new Form("Класс Image"); // объект mydisplay представляет экран телефона
Классы пользовательского интерфейса private Display mydisplay; public MainClassIrnagef ) { mydisplay = Display .getDisplay (this) ; } public void startAppO { // перехватываем исключительную ситуацию try{ / / . загрузка изображения Image im = Image. createlmage ( " /gornakov.png" ) ; // добавляем загруженный файл в форму my form. append (im) ; } catch( Java. io. lOException ex) { } /У Установка обработчика событий для Form myform.addCommand(exitMidlet) ; myf orm.setCommandListener ( t h i s ) ; ' / / Отразить текущий дисплей mydisplay. setCurrent (my form) ; public void pauseAppO {} public void destroy App (boolean unconditional) {} public void commandAction (Command c, Displayable d) { //' Выход из .приложения if (с == exitMidlet) { destroy App (false) ; notifyDestroyed ( ) ;
На рис. 6.13 показан эмулятор телефона, воссоздающий загруженное изображение, посмотрите, насколько больше экран телефона и как разместилось меньшее по размеру изображение на дисплее.
6.7. Класс Font При формировании приложения программисту всегда хочется улучшить его внешний вид и кроме обилия компонентов, создающих списки, таблицы, бегу-
Класс Font
Рис 6.13. Загрузка изображения классом image щие строки, еще имеется класс Font, с помощью которого можно задавать шрифт для текста. Телефоны имеют ограниченные системные ресурсы, поэтому доступно всего несколько шрифтов, которые отличаются по размеру, начертанию, стилю и задаются при помощи констант. Размер шрифта устанавливается при помощи трех констант: , О int SIZE_LARGE - большой шрифт; О static int SIZE_MEDIUM - средний шрифт; Q static int SI ZE_SMALL - маленький шрифт. Стиль можно задавать четырьмя константами: Q static int STYLE_BOLD - жирный шрифт; Q static int STYLE_ITALIC - курсив; ,Q s t a t i c int STYLE_PLAIN - обычный шрифт; Q static int STYLE_UNDERLINED -подчеркнутый шрифт. Начертание шрифта определяется тремя константами: Q static int FACE_MONOSPACE - шрифт с небольшим интервалом; Q static int FACE_PROPORTIONAL - пропорциональный шрифт; Q static int FACE_SYSTEM - системный шрифт. В профиле MIDP 1.0 возможность установки различных шрифтов в приложении имелась только при использовании класса Graphics и метода setFont ( ) . В профиле MIDP 2.0, уже имеется возможность установки шрифта без использования класса Graphics, только при помощи методов из состава классов пользовательского интерфейса. Процесс назначения шрифта текста в программе происходит следующим образом. Вначале создается переменная, ко-
.
Классы пользовательского интерфейса торая будет содержать размер, стиль и начертание шрифта, установленные при помощи метода get Font ( ) класса Font например: Font myFont = Font.getFont(Font.FACE_SYSTEM,Font.STYLE_BOLD, Font.SIZE_LARGE); Переменная myFont теперь содержит шрифт, который можно назначит любому тексту в программе. В профиле MIDP 2.0 для этого достаточно вызвать метод setFont ( ) с необходимыми параметрами. В профиле MIDP 1.0 для назначения шрифта тексту, необходимо использовать класс Graphics, в главе 6 рассматривается эта возможность. В примере к этому разделу будет задействован класс List, создающий список элементов. При создании на экране списка из четырех элементов, каждому элементу будет назначен свой шрифт. В листинге 6.12 содержится код примера создающего различные шрифты элементам списка. Весь исходный код так же содержится на компакт-диске в папке \Code\Listing6_12\src. /**
Листинг 6.12 Класс Font */ import javax.microedition.midlet.*; import javax.microedition.Icdui.*; public class MainClassFont extends MIDlet implements CommandListener // команда выхода из приложения private Command exitMidlet = new Command("Выход", Command.EXIT, 0); // массив иконок Image[] icon = null; // объект класса List . private List mylist; // объект mydisplay представляет экран телефона private Display mydisplay; public MainClassFont() mydisplay = Display.getDisplay(this);
public void startAppO { /7 перехватываем исключительную ситуацию
try{
\
Класс Font
, •
;
lilllBMK
// загрузка изображения Image imaged = Image. createlmage (" /iconO .png" ); Image imagel = Image. createlmage (" /iconl .png" ); Image image2 = Image. createlmage (" /icon2 .png" ); • Image image3 = Image. createlmage ( "/icon3 .png" ); // поместить загруженные изображения в массив icon icon = new Image []{ imaged, imagel, image2 , image3 } ; } catch (Java . io . lOException ex) { } // текст для четырех элементов списка String[] stroka = { "Синий" , "Красный" , "Зеленый" , • "Оранжевый" } ; // назначается шрифт нулевому элементу списка Font fO = Font. getFont (Font . FACE_PROPORTIONAL , Font . STYLE_PLAIN , Font . SIZE_SMALL) ; // назначается шрифт первому элементу списка Font fl = Font .getFont (Font . FACE_SYSTEM , . Font . STYLE_BOLD , Font . SIZE_MEDIUM) ; // назначается шрифт второму элементу списка Font f2 = Font. getFont. ( Font. F AC E_MONO SPACE, Font . STYLE_ITALIC , Font . SIZE_LARGE) ; // назначается шрифт третьему элементу списка Font f3 = Font. getFont (Font. FACE_SYSTEM, Font . STYLE_UNDERLINED , Font . SIZE_LARGE) ; // инициализация объекта mylist mylist = new List ("Класс List"', Choice. EXCLUSIVE, stroka, icon) ; // устанавливается шрифт нулевому элементу списка . mylist . setFont ( 0 , f 0 ) ; // устанавливается шрифт первому элементу списка mylist .setFont (I , fl) ; // устанавливается шрифт второму элементу списка mylist. setFont (2 , f2) ; // устанавливается шрифт третьему элементу списка mylist . setFont (3 , f 3 ) ; // добавить команду выхода mylist. addCommand ( exitMidlet ),mylist . setCommandListener (this) ; // отразить текущий дисплей mydisplay. setCurrent (mylist ) ;
public void pauseApp ( ) { } public void destroy App (boolean unconditional) {} public void commandAct ion (Command c, Displayable d)
Классы пользовательского интерфейса / / выход из приложения if (с == exitMidlet) { destroy Арр ( f a l s e ) ; notifyDestroyed ( ) ;
Основным классом в программе из листинга 6.13, иллюстрирующей работу со шрифтом, является класс MainClassFont. Весь код программы построен на использовании класса List создающем список элементов. В строке кода: Image [] icon = null создается переменная для хранения массива изображений. Конкретно в этом примере будут использованы маленькие иконки, загружаемые каждому элементу списка. Всю группу элементов представляет объект mylist класса List. В методе startApp ( ) происходят основные действия по созданию списка элементов, загрузке изображения и назначению шрифта каждом элементу списка. В четырех строках кода: Image Image Image Image
imaged imagel image2 image3
= = = =
Image. createlmage ( "/iconO .png" ) ; Image. createlmage ( " / i c o n l . png" ) ; Image. createlmage ( "/icon2 .png" ) ; Image. createlmage ( " /iconS .png" ) ;
загружаются четыре различные иконки в виде шариков, окрашенных в синий, красный, зеленый и оранжевый цвет. Все они помещаются в массив: icon = new Image [] { imageO, imagel, image2 , image3}; Далее в программном коде создается массив строковых значений: String [ ] stroka = { "Синий" , "Красный" , "Зеленый" , "Оранжевый" } . Теперь пришло время создать шрифты: Font f O = Font. getFont ( Font. FACE_PROPORTIONAL , Font . STYLE_PLAIN, Font . SIZE_SMALL) ; Font f l = Font .getFont (Font .FACE_SYSTEM, Font . STYLE_BOLD,. Font . SIZE_MEDIUM) ; Font f 2 = Font .getFont (Font . F AC E_MONO SPACE, Font .STYLE_ITALIC, Font .SIZE_LARGE) ; . Font f3 = Font .getFont (Font . FACE_SYSTEM , Font . STYLE_UNDERLINED , Font . SIZE_LARGE) ;
В этих строках создаются четыре переменные f 0 ... f 3 , содержащие различные по стилю, размеру и начертанию шрифты. С помощью созданных переменных
Класс Font Рис 6.14. Эмулятор телефона, на экране которого представлены разные шрифты впоследствии будет производиться установка шрифтов для каждого элемента списка. Список элементов представлен объектом my list и выполнен по типу Exclusive (четыре элемента со своими иконками). В классе List имеется метод setFont ( ) доступный в профиле MIDP 2.0, он и используется в примере. Создав объект класса List, установим шрифт всем элементам списка: mylist.setFont(0 , f0) ; mylist.setFont(1,f1); mylist.setFont(2,f2); mylist.setFont(3,f3); С помощью метода setFont ( ) происходит установка заданного шрифта, содержащегося в переменных f O...f 3. Назначение шрифта происходит по индексам от 0 до 3 в массиве stroka [ ]. В конце кода происходит добавление команды выхода и отображение текущего экрана на дисплее телефона. На рис. 6.14 представлена работа программы из листинга 6.13. К сожалению, ресурсы мобильных телефонов не позволяют воспользоваться обилием шрифтов компьютерной платформы, но и имеющейся базы вполне достаточно для создания разнообразных текстовых элементов. Использование шрифтов в программах значительно улучшает пользовательский интерфейс и придает приложению более изящный вид. В следующей главе будет рассматриваться программирование графики в Java 2 ME, с помощью классов низкоуровневого интерфейса.
Глава 7. Программирование графики Высокоуровневые классы, изученные в главе 6, дают возможность создавать пользовательский интерфейс приложения. По сути, эти классы выполнены в виде шаблонов, используя которые вы можете создавать списки, формы, шрифт, группы элементов, бегущие строки. Но использование таких классов-шаблонов несколько упрощает интерфейс программы, лишая возможности использования графики в программах на Java 2 ME. Иногда в приложении необходимо нарисовать таблицу, линию, квадрат, то есть воспользоваться графикой для создания насыщенной и красочной программы. Для э.тих целей в Платформе Java 2 ME существуют так называемые классы низкоуровневого интерфейса - это классы Canvas и GameCanvas (класс GameCanvas будет рассмотрен в следующей главе), а так же класс Graphics, с помощью которого осуществляется непосредственная прорисовка графики на экране телефона. В самом начале этой главы дается характеристика классам Canvas и Graphics, попутно рассматриваются имеющиеся в составе обоих классов методы, после чего мы приступим к практической части и создадим ряд примеров, иллюстрирующих работу обоих классов.
7.1. Класс Canvas Класс Canvas - это абстрактный класс, поэтому необходимо создавать подклассы для работы с классом Canvas. Абстрактный класс Canvas представляет некий обобщенный графический контекст, что позволяет программе производить прорисовку графики при помощи класса Graphics. Кроме этого, класс Canvas предоставляет возможность в обработке событий полученных с клавиш телефона. Если классы высокоуровневого интерфейса, рассмотренные в главах 5 и б, обрабатывают команды перехода, то с помощью класса Canvas можно получать события с любой нажатой клавиши телефона. Существует ряд так называемых «ключевых кодов» в виде заданных констант, с помощью которых можно назначать игровые действия для клавиш телефона. Все ключевые коды соответствуют стандарту ITU-T и заданны в виде следующих констант: О s t a t i c int DOWN - движение вниз; Q static int FIRE - обычно используется в играх и реализует стрельбу из оружия; Q static int GAME_A - игровая клавиша А; О static int GAME_B - игровая клавиша В; Q static int GAME_C - игровая клавиша С; Q s t a t i c ' i n t GAME_D - игровая клавиша D;
Класс Canvas Q static int KEY_NUMO - клавиша 0; Q static int KEY_NUM1 - клавиша 1; Q static int KEY_NUM2 - клавиша 2; Q static int KEY_NUM3 - клавиша 3; Q static int KEY_NUM4 - клавиша 4; Q static int KEY_NUM5 - клавиша 5; Q s t a t i c int KEY_NUM6 - клавиша 6; Q static int KEY_NUM7 - клавиша 7; Q static int KEY_NUM8 - клавиша 8; Q static int KEY_NUM9 - клавиша 9; Q static int KEY_POUND - клавиша #; Q static int KEY_STAR - клавиша *; Q static int LEFT - движение влево; Q static int RIGHT - движение вправо; Q static int UP — движение вверх. Ключевые коды GAME_A, GAME_B, GAME_C, GAME_D и FIRE предназначены специально для игровых действий и обычно задаются клавишам с цифрами соответственно 2,4,8,6 и 5, но зависят от реализации конкретных моделей телефонов.
7.1.1. Методы класса Canvas Большинство методов класса Canvas обеспечивают обработку низкоуровне-. вых событий. Абстрактный метод void paint (Graphics g) является основным методом, с помощью которого происходит прорисовка графики на экране телефона. Класс Graphics определяет, что именно необходимо рисовать на экране телефона. Разберем основную часть методов класса Canvas: Q int getGameAction(int keyCode) — связывает игровые действия с заданным ключевым кодом; Q int getKeyCode(int gameAct ion) —получает ключевой код игровых действий; Q String getKeyName (int keyCode) - получает ключевой код для клавиши; Q boolean hasPointerMotionEvents ( ) - проверяет поддержку устройством перемещение указателя; Q protected void keyPressed(int keyCode) - вызывается при нажатии клавиши; Q protected void keyReleased(int keyCode) - вызывается при отпускании нажатой клавиши; Q protected void keyRepeated(int keyCode) - повторное нажатие клавиши; Q protected abstract void paint (Graphics g) - прорисовка графики на экране телефона; Q protected void pointerDragged(int x, int у) -определяет перемещение курсора;
пни а а
Программирование графики
protected void pointerPressed(int x, int у) - определяет позицию курсора, при которой должно производится нажатие определенной клавиши; protected void pointerReleased(int x, int у) - определяет позицию курсора в момент отпускания определенной клавиши; void repaint ( ) - повторяет прорисовку; void repaint(int x, int у, int width, int height) -повторяет прорисовку заданной области.
7.2. Класс Graphics При помощи класса Graphics осуществляется двухмерное представление графики на экране телефона. Класс Graphics существует также в составе Java 2 SE, но в платформе Java 2 ME он сильно урезан, всвязи с ограниченными системными ресурсами телефонов. Поэтому имеется возможность рисовать только линии, прямоугольники, дуги и текст. Для окрашивания этих примитивов предусмотрена работа с цветовой компонентой. Система координат, используемая для представления графики в Java 2 ME, переX 0.0 вернута по отношению к обычной Декартовой системе координат. Начало системы координат, находится в левой верхней точке экрана телефона. Положительная ость X проходит по верхней кромке экрана слева направо, а положительная ось Y - сверху вниз по левой стороне экрана, как изображено на рис. 7.1. Такая система координат отнюдь не новшество в программировании двухмерной графики. Идентичная модель координат применяется так же в DirectX и OpenGL Рис. 7.1. Система координат для представления двухмерных сцен, но в Java 2 ME уже в компьютерной графике.
7.2.1. Методы класса Graphics Основные методы класса Graphics обеспечивают прорисовку двухмерной графики. Есть еще несколько методов, с помощью которых можно произвести перемещение системы координат и произвести отсечение (clipping). Основные методы класса Graphics: Q void copyArea(int x_src, int y_src, int width, int height, int x_dest, int y_dest, int anchor) — копирует прямоугольную область из установленных значений в параметрах (x_src , y_src, width, height), в новую область (x_dest, y_dest);
Класс Graphics О void drawArc(int x , int y , int w i d t h , int height, int startAngle, int arcAngle) - рисует контур дуги в виде эллипса; О void drawChar(char character, int x, int y , int anchor) -_ рисует символ; Q void drawChars(char[] data, int o f f s e t , int length, int x, int y , int anchor) - рисует массив символов: Q void drawlmage (Image img, int x, int y, int anchor) рисует изображение; Q void drawLine.fint x l , int y l , int x2 , int y2 ) -рисуетлинию из точки xl и yl, до точки х2 и у2; Q void drawRegion(Image src, int x_src, int y_src, int width, int height, int transform, int x_dest, int y_dest, int anchor) - копирует изображения в заданную область на экран телефона; Q void drawRoundRect(int x, int у, int width, int height, int arcWidth, int arcHeight) - рисует контур прямоугольника, используя закругленные углы; Q void f i l l A r c ( i n t x, int y, int width, int height, int startAngle, int arcAngle) - рисует заполненную цветом дугу; Q void f i l l R e c t { i n t x, int y , int width, int height)- рисует заполненный цветом прямоугольник; Q void fillRoundRect.tint x, int y, int width, int height, int arcWidth, int arcHeight) - рисует заполненный прямоугольник, используя закругленные углы; Q void f i l l T r i a n g l e ( i n t x l , int y l , int x 2 , int y 2 , int x3 , int у З ) - рисует заполненный цветом треугольник; Q int getBlueComponent() — получает синий компонент цвета; Q int getClipHeight О -получает высоту для текущей области отсечения; Q int getClipWidth() - получает ширину для текущей области отсечения; Q int getColor ( ) - получает текущий цвет; Q Font get Font ( ) - получает текущий шрифт; Q int getGreenComponent ( ) - получает зеленный компонент цвета; Q inf getRedComponent ( ) - получает красный компонент цвета; Q void setClip(int x, int у, int width, int height)-устанавливает отсечение заданной области экрана; Q'void setColor(int RGB) - устанавливает цвет при помощи значения RGB; Q void setColor(int red, int green, int blue) - назначает цвет при помощи трех цветовых компонентов red, green и blue; Q void setFont(Font f o n t ) - устанавливает заданный шрифт; Q void setStrokeStyle (int s t y l e ) - задает штриховой стиль рисуемому контексту, используя константы SOLID и DOTTED; Q void translate (int x, int у) - перемещает систему координат в точку х и у.
Программирование графики При использовании некоторых методов, очень часто используется параметр int anchor. С помощью этого параметра задаются различные значения для выбора позиции. Посмотрите на рис. 7.2, где изображен механизм прорисовки текста с выбором определенной позиции. RIGHT
LEFT
TOP
BASELINE
BOTTOM
HCENTER Рис. 7.2. Техника прорисовки текста
Для этих целей в классе Graphics имеются константы, с помощью которых происходит выбор позиции: О static int BASELINE - задает базовую линию; Q static int BOTTOM - сдвигает вниз; О static int HCENTER - центрирует; ГД static int LEFT - сдвигает влево; Q static int RIGHT - сдвигает вправо; Q static int TOP - сдвигает вверх; Q static int VCENTER - используется только при прорисовке изображений, производит вертикальную центровку всего изображения. Можно использовать две константы для выбора позиции. Например, для того чтобы сдвинуть текст влево и вверх, используется комбинация Graphics . LEFT I Graphics .TOP. Далее мы перейдем к практике и изучим модель программирования графики в приложении на Java 2 ME, рассмотрим создание и отрйсовку линий, прямоугольников, дуг и текста. Главное о чем надо помнить при использовании графических элементов - это о размере экрана телефона. Разные модели телефонов имеют свои размеры дисплея; и если вы будете использовать большой по площади экран, например 128x128 пикселей, то на экране с разрешением 101x80, некоторые части графических элементов будут срезаны. Чтобы этого избежать, надо использовать методы класса Canvas; g e t W i d t h O и getHeight ( ) , которые
Рисование линий возвращают размеры ширины и высоты экрана и уже на основании этих данных производить построение графических элементов, производя тем самым адаптацию графического контекста к конкретной модели телефона. Например, чтобы нарисовать горизонтальную линию, не выходящую из зоны видимости, можно воспользоваться следующим кодом: int w = getWidthO; drawLine(20, 2 0 , w-20, w - 2 0 ) ; В своих примерах к этой главе я специально не использую оптимизации графики, для того чтобы исходный код был более понятен. Поэтому после компиляции всех примеров обязательно запустите получившиеся программы на максимальном количестве имеющихся эмуляторов. Особенно попробуйте работу этих программ на эмуляторе DefaultColorPhone из состава среды программирования J2ME Wireless Toolkit 2.1, меня лично очень сильно позабавил результат работы этого эмулятора, а вам, я думаю, предоставит некоторую пищу для размышлений.
7.3. Рисование линий Для того чтобы нарисовать линию нужно воспользоваться методом drawLine ( ) класса .Graphics. Рассмотрим прототип этого метода: public void drawLine(int int int int / -
xl, yl, x2, y2)
'
• ' ,
•,
Параметры метода drawLine ( ) : Q xl - координата начальной точки отрезка по оси X; Q yl -координата начальной точки отрезка по оси Y; Q х2 - координата конечной точки отрезка по оси X; О у2 - координата конечной точки отрезка по оси Y. . Задавая целочисленные координаты точек в методе drawLine ( ) можно нарисовать любую линию заданного размера. Также можно воспользоваться методом setColorO для закрашивания линий цветом и методом setStrokeStyle ( ) для рисования линии в виде пунктира. Рассмотрим пример кода находящийся в листинге 7.1, где с помощью линий рисуется система координат используемая в Java 2 ME. Исходный код листинга 7.1 также находится на компакт-диске в папке \Code\Listing7_l\src. /**'"• Листинг 7.1 Класс Main и класс Line * / • ' , ' ' import javax.microedition.Icdui.*; import javax.microedition.midlet.*;
Программирование графики public class Main extends MIDlet implements CommandListener { // команда выхода из программы private Command exitMidlet = new Command ( "Выход" , Command. EXIT, 0); . public void startAppO { // создаем объект класса Line Line myline = new Line ( ) ; // добавляем команду выхода myline. addCommandf exitMidlet) ; myline. setCommandListener (this) ; Display .getDisplay (this) .setCurrent (myline) ;
public void pauseApp ( ) {} public void destroy App( boolean unconditional) {} public void с ommandAct ion (Command c, Displayable d) { if (c == exitMidlet) { destroy App ( false) ; notifyDestroyed ( ) ;
/**
класс Line определен в файле Line. Java */ import javax.microedition. Icdui . *; public class Line extends Canvas { / / конструктор public Line(){ super (); } public void paint (Graphics g)
Рисование линий // устанавливается синий цвет для линий g.setColor ( O x O O O O f f ) ; // рисуется система координат g.drawLine(20, 2 0 , 9 0 , 2 0 ) g.drawLine(20, 20, 20, 90) g.drawLine(90, 2 0 , 80, 10) g.drawLineOO, 2 0 , 80, 3 0 ) g. drawLi.net 2 0 , 90, 10, 80) g.drawLine(20, 90, 30, 80) // устанавливается красный цвет для трех линий g.setColor(OxffffOOOO) ; // рисуем толстую линию в три пикселя g.drawLine(30, 30, 70, 30); g.drawLine(30, 31, 70, 31); g.drawLine(30, 32, 70, 32); // устанавливаем пунктир g . setStrokeStyle (Graphics . DOTTED) ,// рисуем линию в два (пикселя пунктиром g.drawLine(30, 50, 70, 50); g.drawLine(30, 51, 70, 51);
В листинге 7.1 используются два класса: Main, являющийся основным классом мидлета приложения, и класс Line, в котором происходит работа с графикой. Подразумевается, что оба класса находятся в файлах Main.java и Line.java, это характерно для объектно-ориентированного программирования и в дальнейшем мы будем придерживаться именно такой модели построения изучаемых примеров. Основной класс мидлета Main очень прост. В этом классе создается объект класса Line, добавляется команда выхода из приложения и отражается текущий экран. Класс Line, находящийся в файле Line.java листинга 7.1, рисует набор различных линий. Сам класс Line наследуется от абстрактного класса Canvas. В более сложных программах может использоваться интерфейс Run nable и метод run( ) . Такая техника программирования обычно используется при создании игр, и будет обсуждаться в конце этой главы. Конструктор класса Line использует метод super () позволяющий .обратиться к конструктору своего суперкласса Canvas. Основные же события происходят в методе paint ( ) класса Canvas. В строке кода: g.setColor ( O x O O O O f f ) происходит назначение цвета для любого последующего отрисованного примитива. То есть вызов метода setColorO с заданным цветом действителен до момента последующего вызова метода setColor ( ) , устанавливающего другой
Программирование графики цвет. В этом примере используется метод setColor (RGB), поэтому значение цвета задается восьмеричным значением с помощью нулей и букв. В следующем примере из раздела 7.4 при рисовании прямоугольников будет показана работа метода setColor () с тремя целочисленными параметрами, задающими значение цвета. В строках кода g.drawLine(20, g.drawLine(20, g.drawLine.(90, g.drawLineOO, g.drawLine(20, g.drawLine(20,
20, 20, 20, 20, 90, 90,
90, 20, 80, 80, 10, 30,
20) 90) 10) 30) 80) 80)
рисуется шесть синих линий, образующих систему координат. Толщина всех линий равна одному пикселю - это значение по умолчанию и изменить его нельзя. Для того чтобы нарисовать широкую линию, придется рисовать несколько соприкасающихся одинаковых по размеру линий. g . d r a w b i n e ( 3 0 , 30, 7 0 , 3 0 ) ; g.drawLine(30, 31, 7 0 , 31); g.drawLineOO, 32, 70, 3 2 ) ; Этими строками кода рисуется одна толстая линия шириной в три пикселя. В конце в методе paint ( ) рисуется линия толщиной в два пикселя в виде пунктирной линии. Для этого используется метод setStrokeStyle () и константа DOTTER. На рис. 7.3 изображен эмулятор телефона с результатом работы программы из листинга 7.1. & (1) Nokia 51QQ SDK Re tods Help
7.4. Рисование прямоугольников При создании прямоугольников можно использовать два метода класса Graphics- это drawRectO и f illRect ( ) . При помощи метода drawRect ( ) рисуется только контур прямоугольника, а метод f illRect ( ) позволяет нарисовать прямоугольник уже закрашенным каким-либо цветом, (изначально по умолчанию цвет черный). Оба метода абсолютно идентичны по количеству и назначению параметров, поэтому рассмотрим прототип одного из них, а именно метода drawRect ( ) . public void drawRect(int int int int
x, y, width, height)
Рис. 7.З. Рисование разноцветных линий
Рисование прямоугольников Параметры метода drawRect ( ) : Q х - координата точки по оси X для левого верхнего угла прямоугольника; О у - координата точки по оси Y для левого верхнего угла прямоугольника; О width - ширина рисуемого прямоугольника; G height - высота рисуемого прямоугольника. В составе класса Graphics имеется еще один метод рисующий прямоугольник, но с закругленными углами - drawRoundRect ( ) . Этот метод имеет уже шесть параметров, где первые четыре параметра работают в том же ключе что и методы drawRect ( ) и f illRect ( ) , а два последних параметра определяют степень закругленности углов. В листинге 7.2 рисуется три разных по размеру прямоугольника, и закрашиваются тремя цветами: красным, зеленым и синим. Для закрашивания прямоугольников применяется метод setColor (int red, int green, int blue) с тремя параметрами. Выставляя любое целочисленное значение от 0 до 255 для каждого параметра можно создавать разнообразную цветовую гамму, естественно учитывая при этом цветовые возможности телефона, на котором будет работать эта программа. Для того чтобы определить доступную цветность дисплея телефона, необходимо воспользоваться методами класса Display: О isColorO - если телефон поддерживает цветовую гамму, то возвращает значение true; Q numColor ( ) - определяет количество доступных цветов. На компакт-диске листинг 7.2 находится в папке \Code\Listing7_2\src.
/** Листинг 7 . 2 Класс Main и класс Rectangles */ import javax.microedition.Icdui.*; import javax.microedition.midlet,*;• public class Main extends MIDlet implements CommandListener .,, { // команда выхода из программы private Command exitMidlet = new Command("Выход", Command.EXIT, 0); public void startAppO { // создаем объект класса Rectangles Rectangles myrec = new Rectangles(); // добавляем команду выхода myrec.addCommand(exitMidlet); myrec.setCommandListener(this);
Программирование графики Display .getDisplay (this). .setCurrent (myrec) ;
public- void pauseAppO {} public void destroyApp (boolean unconditional) {} public void commandAct ion (Command c, Displayable d) { if (c == exitMidlet) { destroyApp ( false) ; notifyDestroyedf ) ;
/** класс */
Rectangles определен в файле Rectangles .Java
import j avax. microedit ion. Icdui . * ; public class Rectangles extends Canvas { // конструктор public Rectangles () { super () ; },- . public void paint (Graphics g) { // устанавливается красный цвет g.setColor (255, 0, 0 ) ; / / рисуем первый прямоугольник g.fillRect (/*х*/ 15, /*у*/ 3 0 , / *ширина* / 15, /*высота*/ 20); // устанавливается зеленный цвет g.setColor(0, 255, 0) ; / / рисуем второй прямоугольник g.fillRect (30, 30, 15, 45); // устанавливается синий цвет g.setColor(0, 0, 255); //• рисуем третий прямоугольник g.fillRect(45, 30, 15, 60); // устанавливается синий цвет g.setColor (255, О, О); .// рисуем прямоугольник с закругленными углами
Рисование прямоугольников g.drawRoundRect(70, 3 0 , 4 0 , 4 0 , 10, 10}
В этом примере также используются два класса - класс Main, играющий роль основного класса мидлета и класс Rectangles, где происходит отрисовка графики. Оба класса разделены на два файла Main.java и Rectangles.] ava. В классе Main создается объект класса Rectangles, добавляется команда выхода и показывается текущий экран. Класс Rectangles является подклассом класса Canvas. Прорисовка прямоугольников происходит в методе paint ( ) класса Graphics. g.setColor(255, О , О ) ; В этой строке кода устанавливается красный цвет для прямоугольника размером 15 на 20 пикселей, который рисуется с помощью метода f illRect ( ) . g . f i l l . R e c t ( / * x * / 1 5 , / * у * / 30 ,/*ширина*/ 15 , /*высота*/ 2 0 ) ; .Прямоугольник рисуется закрашенным в красный цвет. Дальше происходит прорисовка еще двух закрашенных в зеленый и синий цвет прямоугольников с размерами соответственно 15x45 и 15x60 пикселей. В конце всего кода в классе Rectangles рисуется контур прямоугольника с закругленными углами. На рис. 7.4 изображен эмулятор телефона с четырьмя нарисованными прямоугольниками.
Рис. 7.4, Рисование четырех прямоугольников
••••Illi 7.5. Рисование дуг
Программирование графики
В английском языке слово arc означает дугу, и именно это слово применяется в документации nojava2 ME. Используя методы drawArc ( ) и f i l l A r c ( ) можно нарисовать как дугу, так и полноценную окружность. Используя оба метода, как вы уже наверно заметили можно нарисовать контур дуги и закрашенную цветом дугу. Методы drawArc ( ) и f illArc ( ) имеют одинаковое количество параметров со сходными действиями. Рассмотрим один из методов - f illArc ( ) . public void f i l l A r c ( i n t int int int int int
x, y, width, height', startAngle, arcAngle)
Параметры метода f illArc ( ) : Q x - расстояние, откладываемое от оси X до мнимой вертикальной касательной к окружности; D у - расстояние, откладываемое от оси Y до мнимой горизонтальной касательной к окружности; Q wight - ширина рисуемой дуги (горизонтальный радиус); Q height - высота рисуемой дуги (вертикальный диаметр); Q startAngle — стартовый угол для начала рисования дуги; Q arcAngle - протяженность дуги (значение 360 замкнет дугу в окружность). На рис, 7.5 изображена схематично техника создания дуги.
height
Рис. 7.5. Техника создания дуги
Рисование прямоугольников В листинге 7.3 приведен пример кода создающего три разноцветных сегмента круга, наложенных друг на друга, и дугу в виде контура. /**
Листинг 7 . 3
Класс Main и класс Arc - */ import javax.microedition.Icdui.*; import javax.microedition.midlet.*; public class Main extends MIDlet implements CommandListener { // команда выхода из программы private Command exitMidlet = new Command("Выход", Command.EXIT, 0); public void startAppO. { // создаем объект класса Arc Arc myarc = new Arc(); // добавляем команду выхода myarc.addCommand(exitMidlet); myarc.setCommandListener(this); Display.getDisplay(this).setCurrent(myarc); public void pauseAppO {} public void destroyApp(boolean unconditional){} public void commandAction (Comma'nd c, Displayable d) if (c == exitMidlet) ,
'•' i>
destroyApp(false); notifyDestroyed (.); } } } /** класс Arc определен в файле Arc.Java рисует дуги */
.
Программирование графики import javax_.microedition . Icdui . * ; public class Arc. extends Canvas { / / конструктор public Arc ( ) { super (); } public void paint (Graphics g) // устанавливается красный цвет g . s e t C o l o r ( 2 5 5 , 0, 0) ; // рисуем первую заполненную цветом дугу g . f i l l A r c ( 1 5 , 15, 6 0 , 6 0 , 45, 3 6 0 ) ; // устанавливается зеленый цвет g.setColor(0, 255, 0); // накладываем вторую дугу поверх первой g.fillArc(15, 15, 60, 60, 45, 180); // устанавливается синий цвет g'. setColor(0, 0, 255) ; // накладываем третью дугу поверх первых двух g-. fillArc(15, 15, 60, 60, 45, 90); // устанавливается синий цвет для дуги в виде контура g.setColor(0, 0, 255); // рисуем контур дуги g.drawArc(5, 5, 80, 80, 30, 180);
В листинге 7.3 используется тот же самый механизм, что и в примерах из листингов 7.2 и 7.1 - создаются два класса: Main и Arc, находящиеся в файлах Main.java и Arc.java. Код этого примера вы найдете на компакт-диске в папке \Code\Listing7_3\src. Все действия по прорисовке дуг осуществляются в методе paint ( ) . g.setColor (25.5 , О , О ) ; g . f i l l A r c ( 1 5 , 15, 6 0 , 6 0 , 45, 3 6 0 ) ; В этих строках кода происходит установка цвета для рисуемой дуги и происходит прорисовка самой дуги. Первые два значения в методе f i l l A r c ( ) - 15 и 15 пикселей задают координаты точки в пространстве, относительно которой будет происходить прорисовка дуги. Значения 60 и 60 пикселей задают ширину и высоту дуги. Значением 45 устанавливается угол для начала рисования дуги (со значением 360 будет нарисована замкнутая окружность). Затем в примере рисуются еще два сегмента зеленого и синего цвета, наложенные поверх первой нарисованной дуги.
1I1IIHM
Вывод текста
7.6. Вывод текста Для вывода текста на экран телефона можно воспользоваться методами drawstring ( ) и drawChar ( ) , рисующими соответственно строку-текста и любой назначенный символ. Текст можно выводить с любым цветом, а также использовать стили начертания, изученные в главе 6. Прототип метода drawstring ( ) выглядит следующим образом: public void drawstring
(String str, int x, int y, int anchor)
Параметры метода drawstring ( ) : Q str - строка текста; Q x и у — задают размер невидимого прямоугольника, в котором происходит расположение текста; О anchor - в этом параметре задается выбор позиции текста внутри невидимого прямоугольника. Здесь используются константы класса Graphics, рассмотренные в разделе 7.2. В листинге 7.4 показан пример вывода текста на экран телефона. Код довольно прост и я думаю, вам не составит труда разобраться в нем самостоятельно. На компакт-диске код примера находится в папке \Code\Listing7_4\src. /**
Листинг 7 . 4 Класс Main и класс Text */ import javax.microedition.Icdui.*; import javax.microedition.midlet.*; public class Main extends MIDlet implements CommandListener { // команда выхода из программы private Command exitMidlet = new Command(«Выход», Command.EXIT, 0); public void startAppO { // создаем объект класса Text Text mytext = new Text(); // добавляем- команду выхода mytext.addCommand(exitMidlet); mytext.setCommandListener(this);
-
*••.
Программирование графики
Display .getDisplay (this) . setCurrent (mytext ) ;
public void pauseApp ( ) {} public void destroyApp (boolean unconditional) {} public void commandAetiont Command c, Displayable d) { if (c == -exitMidlet) { destroyApp ( f a l s e ) ; notifyDestroyed( ) ;
/** класс Text определен в файле Text. Java рисует текст */
import javax.microedition. Icdui . * ; public class Text extends Canvas { / / конструктор public Text () {super ();} public void paint (Graphics g) { // устанавливается цвет g.setColor (10, 80, 200); // рисуем строку текста g. drawstring («Java 2 Micro Edition», 80, 40, Graphics. TOP I Gra^phi с s.HCENTER) ;
7.7. Механизм создания игрового цикла Для создания цикла классом Canvas используется интерфейс Runnable и его единственный метод run ( ) , в котором реализуется цикл прорисовки графики. Рассмотрим в качестве примера класс DemoGraphics и проанализируем его.
Механизм создания игрового цикла public class DemoGraphics extends Canvas implements Runnable {. public void run ( ) { while (true) { // обновление графических элементов repaint ( ) ; // задержка цикла на 20 миллисекунд для обновления состояния дисплея Thread. sleep (20) ; } } public void paint ( Graphics g ) { // код, создающий графические элементы } public void key-Pressed ( int~ keyCode ) { // обработка событий с клавиш телефона при помощи ключевых кодов
В классе DemoGraphics для упрощения опущен основной код, связанный с прорисовкой графики и обработкой событий, поступающих с клавиш телефона. Весь цикл прорисовки графики состоит из трех методов: run ( ) , paint () и key Pressed ( ) . В методе paint ( ) происходит создание и отрисовка графических элементов программы на экране телефона, а метод run ( ) создает цикл, в котором происходит постоянное обновление экрана телефона, связанное, например, с движением графического элемента. События, полученные в результате нажатия клавиш, поступают в метод key.Pressed ( ) , где обрабатываются заданным вами способом. На основании этих событий также может происходить обновление цикла прорисовки графики. В методе run ( ) создается бесконечный цикл while ( true) . В реальной программе необходимо, конечно, предусмотреть выход из бесконечного цикла.. Метод repaint ( ) постоянно обновляет графические элементы. Метод sleep ( ) класса Thread останавливает системный поток на двадцать миллисекунд, для того чтобы отреагировать на все произошедшие изменения, а именно, произвести обработку событий с клавиш телефона и перерисовать графический элемент на экране телефона. Механизм прорисовки графики в профиле MIDP 1.0 строится именно по такому принципу , связанному с изменением состояния графических элементов и называмому игровым циклом.
Программирование графики Теперь давайте рассмотрим как можно больше примеров, реализующих вывод графики на экран, перемещение графических элементов, обработку событий с клавиш телефона, столкновение графического элемента с препятствием и других хитростей, из которых состоят мобильные игры.
7.8. Перемещение квадрата Начнем с самого простого - выведем на экран синий квадрат, прорисованный с помощью метода f i l l R e c t O H заставим переместиться его через весь экран по горизонтали слева на право. Посмотрите на код из листинга 7.5, производящий перемещение квадрата на экране, также пример можно найти на компакт-диске в папке \Code\Listing7_3\src. i
/**
Листинг 7 . 5
Класс Main и класс Draw
*/ import javax.microedition. Icdui . * ; import javax.microedition. midlet . * ; public class Main extends MIDlet implements CommandListener
{ // команда выхода из программы private Command exitMidlet = new Command (" Выход ", Command . EXIT , 0 ) ; public void startAppO
{ // создаем объект класса Draw Draw dr = new Draw ( ) ; // запускаем поток dr .start ( ) ; // добавляем команду выхода dr. addCommand( exitMidlet) ; dr . setCommandListener (this) ; Display. getDisplay (this) .setCurrent (dr) ; .
public void pauseAppO {} public void destroyApp (boolean unconditional) {} public void commandAct ion (Command c, Displayable d)
Перемещение квадрата if (с == exitMidlet) { destroyApp(false); notifyDestroyed();
I**
класс Draw определен в файле Draw.Java перемещает квадрат по экрану */ import javax.microedition.Icdui.*; public class Draw extends Canvas implements Runnable // позиция для перемещения квадрата int position .= 10; // конструктор public Draw() { super () ,- } public void start() // создаем и запускаем, поток Thread t = new Thread(this); t.start(); // метод run() интерфейса Runnable public void run (4. // бесконечный цикл while (true)
.
}
// увеличиваем позицию на 1 position ++; // обновляем экран repaint() ; // останавливаем цикл на 20 миллисекунд try { Thread.sleep(20); } catch (Java.lang.InterruptedException zxz) {}
||
Программирование графики
public void paint(Graphics g) // вычисляем область для перерисовки экрана int x = g.getClipWidthf); int у - g.getClipHeight О; // устанавливаем белый цвет фона g.setColor(Oxffffff); // назначаем перерисовку всему экрану g.fillRect(0,b,x,y); // устанавливается синий цвет квадрата g.setColor(0, 0, 200); // рисуем квадрат g.fillRect(position,40, 20, 20); •
Листинг 7.5 содержит два класса Main и Draw, находящиеся в файлах Main.java и Draw.Java. Основной класс мидлета Main содержит код создающий объект dr класса Draw. Затем он запускает системный поток с помощью метода start ( ) , добавляет команду выхода из программы и отображает текущий дисплей с объектом dr. Класс Draw содержит код, создающий синий квадрат и перемещающий его по экрану. Прежде чем мы начнем рассмотрение кода класса Draw, давайте подумаем, как можно произвести перемещение объекта на экране. Самый простейший способ перемещения объекта по экрану вдоль оси X, заключается в постоянном увеличении, допустим на единицу, позиции этого объекта по оси X. При создании квадрата методом f i l l R e c t ( ) задаются Две координаты по оси X и по оси Y для первоначального вывода квадрата на экран. Поэтому достаточно создать переменную для координаты по оси X и затем в цикле прорисовки увеличивать ее на единицу, перемещая тем самым объект по экрану. / В листинге 7.5 класс Draw наследуется от класса Canvas, что дает возможность воспользоваться методом paint ( ) для рисования графических элементов на экране и реализации метода run ( ) интерфейса Runnable. В методе run ( ) создается цикл, постоянно обновляющий состояние графических элементов. В начале кода класса Draw создается переменная position, отвечающая за координату по оси X для точки вывода квадрата на экран. Конструктор класса Draw вызывает метод super ( ) для использования конструктора своего суперкласса Canvas. В методе start ( ) создается системный поток, который будет запущен в методе run ( ) . Кстати, было бы не плохо предусмотреть выход из потока. Этот пример небольшой и проблем с ним не возникнет, а после разбора листинга 7.5, мы рассмотрим простой механизм, останавливающий системный поток и предусматривающий выход из бесконечного цикла while метода run ( ) . В самом методе run ( ) создается бесконечный цикл, в котором происходит постоянное увеличение переменной position на единицу, благодаря чему квадрат перемещается по оси X слева направо.
Перемещение квадрата В методе paint ( ) вас должны заинтересовать следующие строки кода: int х = g . g e t C l i p W i d t h ( ) ; int у = g . g e t C l i p H e i g h t ( ) ; g.setColor(Oxfff'fff) ; g.fillRect(0,0,х,у); Здесь используется отсечение (clipping) необходимое для корректной прорисовки графики. Если не использовать отсечение, то после того как вы нарисуете квадрат и начнете передвигать его, на экране будет рисоваться слева на право одна толстая синяя линия. То есть будет происходить постоянная перерисовка квадрата в новой позиции по оси X, но при этом будет оставаться и предыдущий нарисованный квадрат. Чтобы этого избежать имеется два способа: можно стирать определенный участок экрана, а можно просто перерисовывать цвет фона всего экрана. Такая операция в Java 2 ME называется отсечением, и для произведения этой операции используются методы: g e t C l i p W i g t h f ) и getClipHeight { ) , производящие отсечение поверхности всего экрана и методы getC l i p X ( ) n g e t C l i p Y ( ) для более точного указания координат заданной области экрана для отсечения. По сути, использование этих методов приводит к простому обновлению всего экрана либо заданной области экрана. В этом примере мы будем использовать перерисовку всего фона экрана. Ширина и высота экрана узнается с помощью методов getClipWigth (') и getClipHeight ( ) , полученные значения сохраняются в переменных х и у. Вызовом метода setColor ( ) устанавливается белый цвет фона и в следующей строке кода задается прямоугольник для области отсечения: g . f i l l R e c t t 0, 0, х, у )'; В конце метода paint ( ) рисуем синий квадрат: g.fillRect(position, 40, 20, 2 0 ) ; С каждым проходом через графический цикл, цвет' фона будет перерисовываться и стирать прошлую позицию квадрата, а квадрат постоянно перерисовывается на новом месте в соответствии со значением переменной position, что и создает иллюзию передвижения объекта по экрану телефона. После компиляции примера из листинга 7.5, на экране появится синий квадрат и пересечет один раз дисплей телефона слева направо. Теперь что касается бесконечного цикла while. В методе run ( ) в реальном приложении необходимо предусмотреть выход из него, а так же позаботиться о прекращений работы потока. Самый простой способ заключается в создании переменной отвечающей за состояние цикла в начале класса Draw, например: boolean z; Дальше в методе start ( ) присвоить этой переменной значение true. public void start()
"
ВШИНИШИ
Программирование графики
т. - true; Thread t = new T h r e a d ( ) ; t. start ( ) ' ; }
А в методе run ( ) использовать значение переменной z для входа в цикл while. while(z) { II код цикла } Для логического конца создается новый метод stop О в классе Draw, назначая переменной z значения false. public void stop() { z = f a l s e ; } Вызовем этот метод в классе Main в методе destroyApp ( ) : public void destroyApp(boolean unconditional) {
}
Z.StOpO ;
7.9. Циклическое передвижение объекта по экрану В листинге 7.5 был нарисован синий квадрат и перемещен один раз вдоль оси X горизонтально слева направо. Но иногда в играх необходимо циклично передвигать объект, используя его, например, в качестве мишени. Возьмем за основу код из листинга 7.5, где перемещается квадрат, и сделаем так, чтобы после пересечения всего экрана и исчезновения, он снова появлялся с другой стороны, создавая подобие циклического перемещения. Алгоритм решения этой задачи заключается в том, чтобы узнать, когда квадрат выйдет из области видимости и в тот же момент нарисовать его с другой стороны экрана и вновь переместить по экрану. Для этого создадим переменную end и присвоим ей значение окончания экрана найденное методом getwidth ( ) (движение происходит по ширине экрана). int end = g e t w i d t h ( ) ; В методе run { ) в самом начале цикла whi 1е будем производить постоянное сравнение позиции квадрата с окончанием экрана: if (position > end) { position = 0;
Циклическое передвижение объекта по экрану Как только квадрат будет выходить из области экрана, его позиция обнулится и квадрат снова будет нарисован в первоначальной позиции, что зациклит движение квадрата. В листинге 7.6 представлен исходный код решающий эту задачу, на компакт-диске пример находится в папке \Code\Listing7_6. /** Листинг 7 . 6 Класс Main и luiacq.Draw */ import javax.microedition. Icdui . *; . import javax.microedition.midlet . *;
public class Main extends MIDlet implements GommandListener { / / команда выхода из программы private Command exitMidlet = new Command (" Выход ", Command . EXIT , 0 ) ; public void startAppO { // создаем объект класса Draw Draw dr = new Draw ( ) ; // запускаем поток dr. start ( ) ; // добавляем команду выхода dr . addCommand (exitMidlet ) ; dr.setCommandListener (this) ; Display .getDi splay (this) . setCurrent (dr) ; public void pauseAppO {} • public void destroyApp (boolean unconditional) {} public void commandAction (Command c, Di'splayable d) { if (c == exitMidlet) { destroyApp (false) ; n6tifyDestroyed ( ) ;
1
Программирование графики класс Draw определен в файле Draw.Java циклическое появление квадрата */ import javax.microedition.Icdui.*; public class Draw extends Canvas implements Runnable { // позиция для перемещения'квадрата int position' = 10; // узнаем ширину экрана' int end = getWidth(); // конструктор public Draw() { super(); } public void start ()' { // создаем и запускаем поток Thread t =• new Thread(this); t.start() ; } // метод run интерфейса Runnable public void run() { // бесконечный цикл while (true) { // сравниваем позицию квадрата if(position > end) { // обнуляем позицию квадрата position = 0; } // увеличиваем позицию на 1 position ++; // обновляем•экран repaint(); // останавливаем цикл на 20 миллисекунд try { Thread.sleep(20); } catch (Java.lang.InterruptedException zxz) {}
Столкновение public void paint(Graphics g) , { // вычисляем область для перерисовки экрана int x = g.getClipWidth(); int у = g.getClipHeight(); // устанавливаем белый цвет фона g.setColorfOxffffff) ; // назначаем перерисовку всему экрану g.fillRect(0,0,х,у); // устанавливается синий цвет квадрата g.setColor(0, 0, 200); // рисуем квадрат g.fillRect(position,40, 20, 20);
7.10. Столкновение В предыдущем разделе 7.9 мы вывели на экран синий квадрат, задали ему вектор движения и перемещали квадрат горизонтально через весь экран. После того как квадрат исчезал, достигнув конца экрана, он циклично появлялся вновь с другой стороны. Следующий пример иллюстрирует столкновение круга и квадрата с препятствием, а именно, окончанием экрана телефона. Оба объекта рисуются независимо друг от друга по высоте экрана и перемещаются параллельно по горизонтали слева на право. По достижению конца экрана оба объекта отталкиваются от конца экрана и начинают движение в обратном направлении. Посмотрите на листинг 7.7, где приводится код программы осуществляющий эти действия. Эта программа состоит из двух файлов Main.java и Draw.java.
У** Листинг 7 . 7 Класс Main и класс Draw */ import javax.microedition.Icdui.*; import javax.microedition.mi.dlet. *,• public class Main extends MIDlet implements CommandListener { // команда выхода из программы private Command exitMidlet = new Command("Выход", Command.EXIT, 0) ; public void startAppO
-
Программирование графики // создаем объект класса Draw Draw dr = new Draw ( ) ; // запускаем поток dr. start () ; / / добавляем команду выхода dr . addCommand(exitMidlet ) ; dr .setcommandListener (this) ; Display .getDisplay (this) . setCurrent (dr) ;
public void pauseApp ( ) {} public void destroyApp (boolean unconditional) {} public void commandAction (Command c, Displayable d) { if (c == exitMidlet) { destroyApp (false) ; notifyDestroyed( ) ;
/** класс Draw определен в файле Draw. Java рисует круг и квадрат v */
import javax. microedition. Icdui .*; . public class Draw extends Canvas implements Runnable { // позиция для перемещения квадрата и круга int position = 0 ; // узнаем ширину экрана int endX = getWidth ( ) ; / / конструктор public Draw() { super ( ) ; } , ' public void start () { // создаем и запускаем поток .Thread t = new Thread ( thi s );
Столкновение t. start() ; // метод run интерфейса Runnable public void run() // бесконечный цикл while (true) // сравниваем позицию if(position > endX) // уменьшаем позицию position = endX—; // увеличиваем позицию на -1 position ++; // обновляем экран repaint(); // останавливаем цикл на 20 миллисекунд try { Thread.sleep(20); } catch (Java.lang.InterruptedException zxz) {}
public void paint(Graphics g) { // вычисляем область для перерисовки экрана int x = g.getClipWidthO ; int у = g.getClipHeight(); .// устанавливаем желтый цвет фона g.setColor(OxffffOO); // назначаем перерисовку всему экрану g.fillRect(0,0,х,у); // устанавливается синий цвет квадрата g.setColor(О, О, 200); // рисуем квадрат g.fillRect(position, 40, 20, 20); // устанавливается красный цвет круга g.setColor(250, 0, 0) ; // рисуем круг g.fillArc(position, 10, 20, 20, 45, 360);
1
Программирование графики
1
Исходный код листинга вы найдете на компакт-диске в папке \Code\ Listing7_7\src. В файле Main.java создается объект класса Draw, запускается системный поток и отражается текущий экран. Файл Draw.java содержит полную реализацию класса Draw. Начальные позиции квадрата и круга определяются переменной position, которой задано нулевое значение. Для того чтобы определить момент столкновения, необходимо знать точку или координаты препятствия. В этом примере как препятствие применяется конец экрана с правой стороны, поэтому с помощью метода getwidth ( ) находится конец экрана. int endX = g e t w i d t h ( ) ; В последствии значение переменной endX будет использовано для определения столкновения. Конструктор класса Draw обращается к конструктору своего суперкласса • Canvas. В методе run() и цикле while с помощью оператора отношения if происходит сравнение текущей позиции двух объектов и конца экрана. if .{
(position > endX) position = endX—;
'}
После того как позиция обоих объектов становится больше значения переменной endX, то есть-квадрат и круг достигают конца экрана, то происходит уменьшение переменной position. Это приводит к движению объектов в обратном направлении. После компиляции прийера на экране появятся два движущихся слева направо объекта. Мы использовали препятствие в виде одной стороны экрана, но точно таким же образом можно определить столкновение для всех сторон экрана или просто для статических объектов. Выполните эти упражнения в качестве домашнего задания, а также внимательно посмотрите на процесс работы примера из листинга 7.7, квадрат и круг все-таки не отталкиваются от кромки экрана, а исчезают. Это происходит, потому что опорная позиция объектов находится в левом верхнем углу и столкновение происходит именно с позицией объектов. Вы знаете размер круга и квадрата, подумайте как можно определить более точную точку столкновения объектов и кромки экрана.
7.11. Перемещение объекта с помощью клавиш Перемещение объекта по экрану телефона с помощью клавиш телефона, это, - пожалуй, самое главное действие в играх. Для передвижения нужно воспользоваться методом key Pressed ( ) и описать код производящий обработку событий получаемых с клавиш телефона. При реализации метода keyPressed ( ) , сначала необходимо вызвать метод getGameAction () для получения ключевого кода с последующей его обработкой. Для обработки полученного ключевого кода
Перемещение объекта с помощью клавиш
1IIIIHHM
можно применить оператор switch и тогда метод keyPressed ( ) может принять следующий вид: protected void key Pressed (int keyCode)
{
// получаем игровые события int act = getGameAction(keyCode) ; / / обработка событий switch (act )
{ case Canvas. LEFT: / / движение влево break ; case Canvas. RIGHT: // движение вправо break; case Canvas. UP: // движение вверх break; case Canvas. DOWN: // движение вниз break; default : break;
Код обработки для клавиш зависит от того, что именно вы желаете сделать с объектом. Давайте возьмем за основу код из листинга 7.5, где был нарисован квадрат, и модернизируем его. Выведем синий квадрат на экран, для этого создадим две переменные posit ionX и positionY, отвечающие за точку вывода квадрата на экран и присвоим им значения близкие к центру экрана. int positionX = g e t w i d t h ( ) / 2 ; int positionY = getHeight ( ) /2 ; При нажатии клавиш можно воспользоваться значениями переменных positionX и positionY для перемещения квадрата по экрану, увеличивая или уменьшая значения этих двух переменных. Значение, на которое вы будете увеличивать или уменьшать переменные, фактически будет обозначать скорость перемещения квадрата по экрану. В листинге 7.8 дается полный код программы перемещения элемента по экрану с помощью клавиш, который можно также найти на компакт-диске в папке \Code\Listing7_8\src. /** Листинг -7 . 8
Программирование графики Класс Main и класс Draw */.','.. import javax.microedition.Icdui.*; import javax.microedition.midlet.*; public class Main extends4 MIDlet implements CommandListener ( { // команда выхода из программы private Command exitMidlet = new Command(«Выход», Command.EXIT, 0);. public void startAppO { // создаем объект класса Draw Draw dr = new Draw.(); // запускаем поток dr.start(); // добавляем команду выхода dr.addCommand(exitMidlet); dr.setCommandListener(this); Display .getDisplay (this) .setCurrent (dr) ,-
public void pauseApp() {} public void destroyApp(boolean unconditional){} public void commandAction(Command c, Displayable d) if (c == exitMidlet) { destroyApp(false); notifyDestroyed(); } }
/** класс Draw определен в файле Draw.j.ava передвижение квадрата с помощью клавиш телефона */
import javax.microedition. Icdui.. *;
-V
Перемещение объекта с помощью клавиш public class Draw extends Canvas implements Runnable { // устанавливаем квадрат в центр экрана int positionX = getwidth( ) /2; // устанавливаем квадрат в центр экрана int positionY = getHeight ( ) /2; // конструктор public Draw () {. super ( ) ; } public void start () { /. •// создаем и запускаем поток Thread t = new Thread ( thi s ); t.. start () ; } // метод run интерфейса Runnable public void run () { // .бесконечный цикл . while (true) { / / обновляем экран repaint ( ) ; // останавливаем цикл на 20 миллисекунд try { Thread. sleep (20).; } catch (Java. lang.InterruptedExcept ion zxz) {}
public void paint (Graphics g) { // вычисляем область для перерисовки экрана int x = g.getClipWidthO ; int у = g.getClipHeight ( ) ; // устанавливаем белый цвет фона g. setColor (Oxffffff) ; / / назначаем перерисовку всему экрану g.fillRect (0,0,х,у) ; // устанавливается зеленный цвет квадрату g. setColor (О, О, 200); // рисуем квадрат g. fillRect (positionX, positionY, 20, 20);
:
Ш1Й
Программирование графики
protected void keyPressed(int keyCode)
{
// скорость передвижения int speed = 3; // получаем игровые события int act = getGameAction(keyCode) ; // обработка событий switch (act) {• // движение влево case Canvas. LEFT: i positionX -= speed; break; // движение вправо case Canvas . RIGHT : positionX += speed; break; // движение вверх case Canvas. UP: positionY -= speed; break; // движение вниз case Canvas. DOWN: positionY += speed; break; default: break;
В следующей главе рассматриваются игровые классы, доступные в профиле MIDP 2.0 и значительно упрощающие создание игрового цикла, а также игровой графики.
Глава 8. Техника создания игр Рынок мобильных телефонов развивается стремительными темпами. Все больше телефонов имеют поддержку технологии Java. Веянье игровой индустрии захватило и мобильные телефоны, поэтому платформа Java 2 ME позиционируется в большей степени как игровая платформа для мобильных телефонов. При разработке игр под профиль MIDP 1.0 программист сталкивается с массой проблем в виде написания большого количества собственных классов для создания игрового процесса, рисование графики, уровней и так далее. В профиль MIDP 2.0 добавлено пять игровых классов, значительно упрощающих создание мобильных игр, это: , Q GameCanvas — абстрактный класс, содержащий основные элементы игрового интерфейса; Q Layer - абстрактный класс, отвечающий за уровни представляемые в игре; Q LayerManager - менеджер уровней; Q Sprite - представляет на экране спрайтовое изображение; Q TiledLayer — отвечает за создание фоновых изображений. Все вышеперечисленные классы доступны только в профиле MIDP 2.O. Также можно воспользоваться этими классами и в программировании телефонов Siemens под профиль MIDP 1.0, импортировав пакет com.siemens.mp.colqr_game. Компания Siemens входит в экспертную группу MIDP Expert Group и, по всей видимости, на базе уже имеющихся игровых классов от компании Siemens были созданы игровые классы для профиля MIDP 2.O. * При использовании игровых классов профиля MIDP 2.0, построение мобильной игры основано на системе уровней. Формируя игру, программист создает необходимое ему количество уровней. Каждый из уровней содержит набор графических элементов, например, можно создать уровень с фоновым изображением, уровень с препятствиями, уровень с игровыми бонусами, уровень с главным персонажем игры. После этого все имеющиеся уровни компонуются воедино, накладываются один уровень на другой и прорисовываются на экране телефона. Контроль над всеми уровнями, осуществляется при помощи класса LayerManager менеджера уровней. Обилие методов предоставляемых игровыми классами позволяет отслеживать всевозможные столкновения, перемещения, анимацию и множество других функций, что значительно упрощает процесс создания мобильных игр. В этой главе, сначала вы познакомитесь с устройством всех игровых классов, а затем будет создан ряд примеров иллюстрирующих работу и взаимодействие игровых классов профиля MIDP 2.O.
•
Щ
Техника создания игр
8.1. Класс GameCanvas Абстрактный класс GameCanvas составляет основу интерфейса всей создаваемой игры. Этот класс отвечает за прорисовку экрана, улучшая механизм работы игрового цикла и не используя при этом входные системные потоки. Весь игровой процесс может быть сосредоточен в одном цикле метода run ( ) интерфейса Runhable. Игровой цикл, используемый классом GameCarivas, отличается от аналогичного цикла применяемого классом Canvas. Типичная проблема игрового цикла класса Canvas заключается в том, что он разбит на несколько потоков. Вывод графики происходит в одном методе, обработка событий с клавиш - в другом, а изменение состояния игрового процесса в третьем. Такая модель работы может давать сбои, поэтому в классе GameCanvas была придумана более изящная конструкция игрового цикла, располагающаяся в одном единственном цикле. • public void run ( ) { . Graphics g = getGraphics ( ) ; while (true) { // метод, обрабатывающий нажатия клавиш с телефона inputKey ( ) ; // метод, прорисовывающий графику GameGraphics ( ) ; // копирует графические элементы на /экран из . внеэкранного буфера f lushGraphics ( ) ; } Система прорисовки игровой графики построена на использовании двойной буферизации, без которой невозможно создать ни одной хорошей компьютерной игры. Смысл механизма двойной буферизации заключается в использовании внеэкранного буфера. Вся игровая графика рисуется во вторичном или внеэкран-, ном буфере и только после полного цикла отрисовки, копируется непосредственно на экран с помощью метода f lushGraphics ( ) . При этом улучшается качество самой графики и, что самое главное, до тех пор, пока игровой процесс не обновится, обработка событий с клавиш телефона является недоступной. Сама же обработка событий с клавиш упрощена с помощью метода getKeyState ( ) . Вы просто определяете нажатую клавишу и описываете соответствующие игровые действия для нее. Изменены некоторые названия констант для клавиш телефона. Обработка событий с клавиш телефона происходит с помощью следующих констант: Q static int DOWN_PRESSED - движение вниз; Q static int FIRE_PRESSED.- реализует стрельбу из оружия;
Класс Layer Q Q Q Q Q Q Q
static static static static static static static
ННМННИШ int int int int int int int
GAME_A_PRESSED - игровая клавиша А; GAME_B_PRESSED - игровая клавиша В; GAME_C_PRESSED - игровая клавиша С; GAME_D_PRESSED - игровая клавиша D; LEFT_PRESSED - движение влево; RIGHT_PRESS'ED - движение вправо; UP_PRESSED - движение вверх.
Использование констант значительно упрощает, работу с объектом, а с помощью метода getKeyStates ( ) класса GameCanvas, можно определить, какая именно клавиша нажата в данный момент. Проанализируем методы класса GameCanvas: О! void f lushGraphics ( ) - копирует изображение из внеэкранного буфера на экран; Q void flushGraphics(int x, int y , int width, int height) копирует изображение из внеэкранного буфера на экран в заданный по размеру прямоугольник; Q protected Graphics getGraphics ( ) - получает графические элементы для представления их в последствии классом GameCanvas; Q int getKeyStates ( ) . — определяет какая из клавиш нажата; G void paint (Graphics g) — рисует графические элементы, представленные классом GameCanvas. Класс GameCanvas создает основной цикл игрового процесса в одном потоке, наблюдает за событиями, получаемыми с клавиш телефона на основе которых производит постоянное обновление экрана.
8.2. Класс Layer Абстрактный класс Layer задает основные свойства для всех созданных уровней игры. Класс Layer имеет два подкласса TiledLayer и Sprite. При создании любых других подклассов класса Layer необходимо реализовать метод paint ( ) в этих классах, чтобы иметь возможность рисовать созданные уровни на экране телефона, представляемом классом Graphics. С помощью методов класса Layer можно задавать размер и позицию уровня. Q int getHeight ( ) - получает высоту экрана; О int getwidth ( ) - получает ширину экрана; О int getx ( ) - получает горизонтальную координату уровня; Q int getY ( ) - получает вертикальную координату уровня; Q void move (int dx, int dy) - перемещает уровень на dx и dy координаты; Q abstract void paint (Graphics g) - рисует уровень; Q void setPosition ( i n t x, int у ) - устанавливает уровень в позицию, обозначенную в координатах х и у.
ствляет представление любого количества уровней на игровом поле. Для создания объекта нужно воспользоваться конструктором класса LayerManager. G LayerManager ( ) - создает уровень. А чтобы добавить уровни в игру необходимо использовать следующие методы: О void append (Layer 1) - добавляет уровень в менеджер уровней; Q Layer getLayerAt (int index) - получает уровень с заданным индексом; V
Техника создания игр
8.3. Класс TiledLayer С помощью класса TiledLayer создается фон игровой сцены. Фоновое изображение выполняется в виде одинаковых по размеру ячеек как показано на рис. 8.1.
Техника создания игр int getSize ()-получает общее количество уровней; void insert (Layer I, int index) - подключает новый уровень в заданный индекс;. Q void paint (Graphics g, int x, int у ) - представляет текущий менеджер уровней в заданных координатах; Q void remove (Layer 1) - удаляет уровень из менеджера уровней. Предположим, у вас имеется четыре уровня: фон, игрок, препятствия и артефакты. Для того чтобы связать все четыре уровня воедино, создается объект класса LayerManager и вызывается метод append ( ) . Например: La'yerManager 1m = new LayerManager ( ) ; 1m.append(fon); 1m.append(igrok); 1m.append(prep); , 1m.append(artf);
,
И все! Четыре перечисленных уровня отражается на игровом поле.
8.5. Класс Sprite Механизм работы с объектом класса Sprite идентичен модели работы с классом TiledLayer. Но если класс TiXedLayer в основном _отвечает за фоновое изображение, то с помощью класса Sprite рисуются на экране основные анимированные герои, космические корабли, машины, люди, звери, артефакты и так далее. Изображение, загружаемое в игру, может быть выполнено в виде анимационной последовательности. Количество рисунков в анимационной последовательности неограниченно, а отсчет происходит от нуля. Располагаться рисунки могут как в виде столбца, так и в виде колонки, в зависимости от ваших предпочтений. Каждый рисунок анимационной последовательности называется фреймом. Фрейм может быть любого размера по ширине и высоте, но все фреймы должны быть одинаковых размеров. Размер фрейма должен быть известен, потому что он используется при создании объекта класса Sprite. Есть три конструктора класса Sprite каждый из которых можно использовать при создании объекта класса Sprite. Q Sprite (Image image) - создает не анимированный спрайт; Q Sprite(Image image,-int frameWidth, int frameHeight)- создает анимационный спрайт, взятый из заданного фрейма; О Sprite (Sprite s) —создает спрайт из другого спрайта. Для перехода по фреймам исходного изображения, а также определения столкновения между объектами используются методы класса Sprite. Q boolean coll'idesWithtSprite s, boolean pixelLevel) - определяет столкновение между спрайтами; G boolean collidesWith(TiledLayer t , boolean pixelLevel)определяет столкновение между спрайтом и препятствием, нарисованным при помощи класса TiledLayer;
Создание фонового изображения Q Q Q Q О Q
int getFrame ( ) - получает текущий фрейм; void next Frame () —осуществляет переход на следующий фрейм; void paint (Graphics g) - рисует спрайт; void prevFrame () —осуществляет.переход на предыдущий фрейм; void setFrame(int sequencelndex)-устанавливает заданный фрейм; void setFrameSequence (int [ ] sequence) - устанавливает определенную фреймовую последовательность; О void setImage(Image img, int frameWidth, int frameHeight)изменяет изображение спрайта на новое изображение; О void setTrans form (int transform) - производит трансформацию спрайта. Q public void defineReferencePixel (int x, int у ) — изменяет опорную позицию спрайта, перенося ее в точку с координатами х и у.
Метод def ineReferencePixel ( ) изменяет опорную позицию спрайта, но для чего это нужно? Опорная позиция для спрайта задается левым верхним углом, но не всегда это удобно, поэтому опорную позицию можно перенести, в центр спрайта. Например, если спрайт сделан в виде машины, то при вращении вокруг своей оси, если опорная позиция перенесена в центр, вращение будет правдоподобным. Но если не переопределить позицию, то вращение произойдет в точке левого верхнего угла спрайта и выглядеть это будет не вполне естественно, как будто у машины пробито одно из колес. Для этого вызывается метод def ineReferencePixel ( ) с заданными координатами и переопределяет опорную позицию, например в центр спрайта: •I defineReferencePixel(frameWidth / 2, frameHeight / 2 ) ; 'Метод s e t T r a n s f o r m ( ) производит трансформацию спрайта, вращая или зеркально отображая спрайт вокруг своей оси с помощью следующих констант: Q static int TRANS_MIRROR; Q Q Q Q
static static static static
int int int int
TRANS_MIRROR_ROT180; TRANS_MIRROR_ROT270; • TRANS_MIRROR_ROT90; TRANS_NONE;
a static int TRANS_ROT180; D static int TRANS_ROT270; D s t a t i c int TRANS_ROT90.
Посмотрите на рис. 8.2, где очень привлекательно показаны константы для различных состояний спрайта. Рассмотрев классы GameCanvas, Layer, Sprite, TiledLayer и LayerManager, перейдем к практическим занятиям этой главы.
8.6. Создание фонового изображения С помощью класса Ti ledLayer можно создавать любое количество уровней, накладывая их друг на друга, а с помощью менеджера уровней, представленного
Техника создания игр
TRANS.MIRROR
TRANS_MIRROR_ROT180
классом LayerManager, отслеживать все имеющиеся уровни. В качестве примера будет создан фон на основе элементов разметки игрового поля. Фоновое изображение загружается из файла fon.png. Само изображение выполнено в виде шести ячеек размером 15x15 пикселей. В листинге 8.1 находится код примера создающего фоновое изображение. Ознакомьтесь с листингом, а потом мы перейдем к анализу этого примера.
/** TRANS.ROT90
TRANS_MIRROR_ROT90
TRANS_HIRROR_ROT270
Рис. 8.2. Константы трансформации
листинг 8.1 класс MainGame */ import javax.micro-edition. Icdui . *; import javax.microedition.midlet.*;
public class MainGame extends MIDlet implements CommandListener { // команда выхода private Command exitMidlet = new Command("Выход", Command.EXIT, 0) ; // объект класса MyGameCanvas private MyGameCanvas mr; public void startAppO { // обрабатываем исключительную ситуацию try{ // инициализируем объект класса MyGameCanvas mr = new MyGameCanvas(); // запускаем поток mr.start(); // добавляем команду выхода mr.addCommand(exitMidlet); mr.setCommandListener(this); // отражаем текущий дисплей Display.getDisplay(this).setCurreht(mr); }catch (Java.io.lOException zxz) {};
Создание фонового изображения public void pauseApp ( ) {} public void destroyApp (boolean unconditional) { // останавливаем поток if(mr != null) mr.stopO;
public void с oiranandAct ion (Command c, Displayable d) { if (c == exitMidlet) { destroyApp ( f a l s e ) ; notifyDestroyed( ) ;
/** Файл MyGameCanvas.j ava класс MyGameCanvas '*/ import java.io.IOException; import javax.microedition.Icdui.*; import javax.microedition.Icdui.game.*; public class MyGameCanvas extends GameCanvas implements Runnable { // создаем объект класса TiledLayer private TiledLayer fonPole; // создаем объект класса LayerManager private LayerManager 1m; // логическая переменная для выхода из цикла
boolean z; public MyGameCanvas() throws lOException { // обращаемся к конструктору суперкласса Canvas super(true); // инициализируем fonPole fonPole = Fon(); // создаем менеджер уровней 1m = new LayerManager();
HHHIS
Техника создания игр
// добавляем объект fonPole к уровню 1m. append ( fonPole) ; .
public void start (.) { z = true; // создаем и запускаем поток Thread t = new Thread (this) ; t. start () ; } //* метод, создающий объект класса TiledLayer' и загружающий фоновое изображение */ public TlledLayer Fon () throws lOException { // загрузка изображения из файла ресурса Image im = Image. createlmage (" /fon.png" ); // создаем объект класса TiledLayer fonPole = new TiledLayer (/*столбцы*/10 , /*строки*/10 , /*изображение*/1т, /* ширина* /15 , /*высота*/15) ; // разметка игрового поля int[] pole = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 1, 1, 5/5, 5, 1, 1, 5, 1, 1, 1, 1,- 1, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, б, 6, 1, 1, 1, 1, 1, 1, б, 6, 6, б, 2, 4, 4, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2„ 4, 4, 4, 3, 3 , 3 , 3, };
/ / цикл , считывающий разметку поля for(int i, = 0; i < pole . length; i++) { /* присваеваем каждому элементу игрового поля определенную ячейку изображения im*/ • fonPole. setCellfi % 10, i / 10, polefi]); } return fonPole;
Создание фонового изображения
НШННН
public void stop(){ z = false; } public void run() С
//, получаем графический контекст Graphics g = getGraphics ( ) ; while (z) {
/ / рисуем графические элементы init(g) ; // останавливаем цикл на 20 миллисекунд try { Thread. sleep (20) ; } catch ( Java. lang. InterruptedException zxz) { } ;
private void init (Graphics g) { // белый цвет фона для перерисовки экрана g.setColor ( O x f f f f f f ) ; // размер перерисовки экрана ' g . f i l l R e c t ( 0 , 0 , getWidth( ) , getHeight ( ) ) ; // рисуем уровень с левого верхнего угла дисплея lm.paint(g, О, О ) ; // двойная буферизация f lushGraphics ( ) ;
Листинг 8.1 состоит из двух классов MainCanvas и MyGameCanvas, находящихся в файлах MainCanvas.java и MyGameCanvas.java. Анализ листинга начнем с класса MyGameCanvas. В первых строках кода этого класса объявляются два объекта классов TiledLayer и Lay erManager, а так же логическая переменная z. private TiledLayer fonPole; private LayerManager 1m; boolean z; Объект fonPole класса TiledLayer будет отвечать за фоновое изображение. Объект 1т класса LayerManager является менеджером уровней. Логическая переменная z необходима для прерывания цикла в методе run ( ) и для окончания системного потока, в котором происходит работа всего игрового цикла. В конструкторе MyGameCanvas происходит инициализация объекта fonPole класса TiledLayer и объект I'm класса LayerManager. Инициализированный объект fonPole добавляется менеджером уровней к текущему уровню для
Техника создания игр представления на экране телефона/Обратите внимание, объект fonPole инициализируется с помощью метода Fon ( ) . Image im = I m a g e . c r e a t e l m a g e ( " / f o n . p n g " ) ; fonPole= new TiledLayer(/*столб*/10,/*строки*/10, im, /*ширина*/15,/*высота*/15); В этих двух строках происходит загрузка исходного изображения из файла ресурса и создание объекта fonPole с помощью конструктора класса TiledLayer. Вся разметка игрового поля выполнена в виде десяти строк и десяти столбцов. Первые два параметра конструктора класса TiledLayer как раз и отвечают за количество столбцов и строк. Третий параметр конструктора - это исходное изображение, выполненное в виде шести ячеек, каждая размером 15x15 пикселей. Два последних параметра конструктора класса TiledLayer определяют ширину и высоту ячейки. При создании объекта класса TiledLayer необходимо быть внимательным и ука'зывать реальные размеры одной ячейки. Если размер одной ячейки будет, предположим 20x20 пикселей, а вы обозначите как 15x15 пикселей, то в итоге ячейки изображения загружены не будут. Дальше в методе Fon ( ) происходит разметка игрового поля выполненного в виде десяти столбцов и десяти строк. i n t [ ] pole = { 5, 5, 1, 5, 1,1, 1, 1, 1, 1, 1, 1, 1, 1, 2,4, 2, 2, 2, 2,
5, 5, 5, 1, 1, 1, 1, 4, 2, 2,
5, 5, 5, 1, 1, 1, 1, 4, 4, 4,
5, 5, 5, 5, 1, 1, 1, 4, 4, 4,
5, 5, 5, 5,. 5, 1, 1, 4, 4, 4,
5, 5, 5, 5, 5, 1, 6, 3, 3, 3,
5, 5, 5, 1, 1, 1, 6, 3, 3, 3,
5, 5, 5, 1, 1, 6, 6, 3, 3, 3,
5, 5, 5, 5, 1, 6, 6, 3, 3, 3,
};
Все строки и столбцы состоят из элементов. Отсчет ячеек происходит от единицы и выше. Присвоение номера ячейки исходного изображения одному из элементов и организует разметку игрового поля, которое в последствии будет рисоваться на экране..Единственное о чем нельзя забывать - это о размере дисплеев реальных телефонов. Если вы имеете десять столбцов и размер каждой ячейки 15 пикселей по ширине, то в итоге ваше игровое поле в ширину будет 10x15 = 150 пикселей. Не каждый телефон может похвастаться таким разрешением, поэтому при создании игрового поля нужно учитывать эти нюансы. Вслед за разметкой игрового поля в методе Fon ( ) происходит считывание всех элементов с помощью цикла for.
Обработка событий с клавиш телефона f o r f i n t i = 0; i < pole.length; i + + ) { • , •fonPole.setCell(i % 10, i / 10, p o l e [ i ] ) ; } Присвоение номера ячейки определенному элементу происходит при помощи метода setCell ( ) . В этом методе первый параметр-номер столбца, второй - номер строки и последний - номер ячейки изображения. Здесь главное не запутаться, потому что номера столбцов и строк начинаются с нуля из-за того, что это обычный массив данных, а все массивы, как вы знаете, ведут свой отсчет с нуля, тогда как ячейка исходного изображения начинается с единицы. Сразу возникает вопрос, а почему не произвести отсчет тоже с нуля, чтобы не было путаницы? Дело в том, что отсчет и производится с нуля, но число ноль - это своего рода зарезервированное значение для ячеек изображения. Нулевое значение может использоваться, но оно не загружает ничего, поэтому отсчет ячеек ведется с единицы. С методом Fon ( ) мы разобрались, перейдем к методу init ( ) . g.setColor(Oxffffff); g.fillRect ( 0 , 0, getWidthO, getHeight()); В этих строках кода происходит постоянная перерисовка фона экрана. Эти действия вы производили в главе 7, когда разбирали механизм отсечения. С помощью метода paint ( ) рисуется уровень. Начало точки вывода уровня задано точкой 0,0, что соответствует началу системы координат. И последний метод f lushGraphics ( ) осуществляет двойную буферизацию, копируя графические элементы из внеэкранного буфера на экран. В методе run ( ) происходит остановка игрового цикла. Перед тем как цикл создается с помощью оператора while, методом getGraphics ( ) происходит получение графического контекста, что и является одним из достоинств механизма игрового цикла в профиле MIDP 2.0. В файле MainGame.java создается основной класс мидлета MainGame. В методе startApp ( ) производится создание объекта рассмотренного класса MyGameCanvas, добавляется команда выхода, запускается системный поток и отражается текущий дисплей. В методе destroyAppO происходит остановка потока методом stop ( ) класса MyGameCanvas.
8.7. Обработка событий с клавиш телефона В профиле MIDP 2.0 предусмотрена улучшенная обработка событий получаемых с клавиш телефона. Используя метод getKeyState ( ) можно определять состояние клавиш телефона и действовать адекватным образом. В демонстрационном примере к этому разделу мы выведем на экран мячик, созданный при помощи класса MySprite являющимся подклассом класса Sprite. В листинге 8.2 представлен код примера, в котором на экране рисуется синий мяч, а с помощью клавиш телефона Up, Down, Left и Right этот мяч можно передвигать по экрану. Листинг 8.2 состоит из трех классов: MainGame, MyGameCanvas и MySprite,
Техника создания игр расположенных в трех разных файлах MainGame.java, MyGameCanvas.java и MySprite.java. /** Листинг 8 . 2
класс MainGame */ import javax.microedition. Icdui . * ; import javax.microedition.midlet . * ; public class MainGame extends MIDlet implements CommandListener { // команда выхода private Command exitMidlet = new Command ( "Выход" , Command . EXIT , 0 ) ; // объект класса MyGameCanvas private MyGameCanvas mr; public void start App() { '/I обрабатываем исключительную ситуацию try{ / / инициализируем объект класса MyGameCanvas mr = new MyGameCanvas ( ) ; // запускаем поток mr .start ( ) ; // добавляем команду выхода mr . addCommand (exitMidlet ) ; mr. setcommandListener (this) ; // отражаем текущий дисплей Display .getDisplay (this) .setCurrent (mr) ; }catch ( Java. io. lOException zxz) { } ; public void pauseApp ( ) {} public void destroy App( boo lean unconditional) { // останавливаем поток if(mr != null) mr.stopO; public void commandAct ion (Command c, Displayable d)
Обработка событий с клавиш телефона if (с == exitMidlet) { destroyAppf false) ; notifyDestroyed ( ) ;
/** файл MyGameCanvas . Java класс MyGameCanvas */
import j ava . io . * ; import javax.microedition. Icdui .*; import javax.microedition. Icdui .game. * ; public class MyGameCanvas- extends GameCanvas implements Runnable { // создаем объект класса MySprite private MySprite bol; // создаем объект класса LayerManager private LayerManager 1m; /7 логическая переменная boolean z; public MyGameCanvas () throws lOException { // обращаемся к конструктору суперкласса Canvas super (true) ; // загружаем изображение Image im = Image. createlmage (" /bol .png" ); . // инициализируем объект bol bol = new MySprite (im, 23, 23); // выбираем позицию в центре экрана bol.setPosition(getWidth() /2 , getHeight ( ) /2) ; // инициализируем менеджер уровней 1m = new LayerManager ( ) ; // добавляем объект bol к уровню 1m. append (bol) ; public void start ( )
I I I I i
Техника создания игр
z = true; // создаем и запускаем поток Thread t = new Thread (this) ; .' t. start (); } // останавливаем поток public void stop(){ z = false; } public void run ( ) { // получаем графический контекст Graphics g = getGraphics ( ) ; while (z) { / / обрабатываем события с клавиш телефона inputKey ( ) ; // рисуем графические элементы init (g) ; // останавливаем цикл на 20 миллисекунд try { Thread. sleep (20 ); } catch ( Java. lang. JnterruptedExcept ion zxz) {};
private void inputKey ( ) { // определяем нажатую клавишу int keyStates = getKeyStates ( ) ; / / код обработки для левой нажатой клавиши if ((keyStates & LEFT_PRESSED) != 0) bol .moveLeft ( ) ; / / код обработки для правой нажатой клавиши if ((keyStates & RIGHT_PRESSED) != 0) bol.moveRight ( ) ; // код обработки для клавиши вверх if ( (keyStates & UP_PRESSED) != 0) bol .moveUp ( ) ; // код обработки для клавиши вниз if ((keyStates & DOWN_PRESSED) != 0) bol .moveDown( ) ; private void init (Graphics g) { // белый цвет фона g.setColor(Oxffffff) ; // перерисовываем экран
Обработка событий с клавиш телефона g.fillRect(0, 0, getwidth ( ). , getHeightO) // рисем уровень в точке 0,0 1m. paint (g, 0 , 0) ; // двойная буферезация f lushGraphics ( ) ;
/** файл My Sprite. Java класс MySprite */ import javax.microedition. Icdui . *;.; import javax. microedition. Icdui .game. *; public class MySprite extends Sprite , { / / конструктор public MySprite (Image image, int fw, int fh) ( // обращаемся к конструктору суперкласса super(image, fw, fh) ; > // метод для клавиши Left public void moveLef t ( ) { // передвигаем спрайт move (-1,0) ; } // метод для клавиши Right public void moveRightO {' // передвигаем спрайт move (1,0) ; } // метод для клавиши Up public void moveUp ( ) { / / передвигаем спрайт move ( 0 , - 1 ) ; } // метод для клавиши Down public' void moveDown ( )
Техника создания игр
{
.// передвигаем спрайт move(0,1);
В файле MySprite.java находится класс MySprite, с которого и начнем рассмотрение листинга. Конструктор класса MySprite обращается к конструктору своего суперкласса Sprite. super(image, fw, fh); Этот конструктор имеет три параметра — это исходное изображение спрайта, ширина и высота фрейма. Спрайт, как вы помните, может иметь анимационную последовательность, поэтому необходимо точно знать ширину и высоту одного фрейма, при обязательном условии, что все фреймы спрайта должны быть одного размера. В этом примере мы не используем анимационной последовательности, и можно было обойтись и более простым конструктором суперкласса Sprite. Для передвижения спрайта по экрану телефона созданы методы moveLeft ( ) , moveRight (.), moveUp () и moveDown ( ) , в основу которых положены вызовы метода move ( ) . Метод move ( ) имеет два параметра - это координаты по осям X и Y. Задавая необходимое смещение на 1, 2, 3 и более пикселей по одной из осей, вы будете производить движение объекта по экрану. Класс MyGameCanvas работает по схеме, использованной в разделе 8.6, с той лишь разницей, что вместо фонового изображения загружается спрайт в виде мячика. В конструкторе класса MyGameCanvas происходит загрузка исходного изображения bol.png, это и есть наш мячик или спрайт. Спрайт размером 23x23 пикселя. При создании объекта bol класса MySprite bol = new MySprite(im, 23, 2 3 ) используется изображение bol.png, затем в конструкторе класса MyGameCanvas происходит выбор позиции для первоначальной отрисовки спрайта на экране с помощью метода setPosition ( ) . Мячик рисуется в центре экрана и добавляется методом append ( ) к уровню. В методе r u n ( ) в игровом цикле происходит вызов двух методов. Метод init ( ) производит рисование всех графических элементов с помощью менеджера уровней, а метод inputKey ( ) осуществляет обработку нажатий клавиш телефона. private void inputKey() { int keyStates = g e t K e y S t a t e s ( ) ; if ((keyStates & LEFT_PRESSED) >.= 0) bol .moveLeft ( ) ; if ((keyStates & RIGHT^PRESSED) != 0) bol.moveRight(); if ((keyStates & UP_PRESSED) != 0) b o l . m o v e U p ( ) ; if ((keyStates & DOWN_PRESSED) ! = - Q ) bol.moveDown();
Анимация в игровом процессе
(IIIII
В методе inputKeyO происходит определение нажатой клавиши посредством метода getKeyState ( ) . Весь остальной код в методе inputKey ( ) использует оператор if для обработки нажатых клавиш, вызывая соответствующие методы moveLeftO', moveRight ( ) , moveUpO или moveDown ( ) для перемещения объекта по экрану. В классе MainGame из файла MainGame.java создается объект класса MyGameCanvas, запускается системный поток и отражается текущий экран. В этом примере использовался спрайт файла ресурса bol.png состоящий из одного фрейма размером 23x23 пикселя. В следующем разделе мы рассмотрим технику анимации спрайтов в играх, и будем использовать спрайт, состоящий уже из нескольких фреймов.
8.8. Анимация в игровом процессе Анимация в игровом процессе строится на основе последовательной цепочки рисунков. Как вы уже знаете, отдельно взятый рисунок из анимационной последовательности в Java 2 ME называется фреймом. Для того чтобы осуществить плавную анимацию в игре, необходимо выполнить ряд сменяющих друг друга рисунков. Посмотрите на рис. 8.3, где изображен матрос с флажками.
Рис. 8.3. Анимационная последовательность На рис. 8.3 все фреймы выполнены в виде горизонтальной цепочки, но это не обязательное условие, можно расположить фреймы любым удобным образом. Не забывайте о том, что отсчет начинается с нуля и идет слева направо и сверху вниз. Анимация повсеместно используется в компьютерных и мобильных играх. Вы наверно замечали, что при перемещении в игре персонажа, он производит ряд повторяющихся движений, создавая видимость игрового цикла. Такие элементарные движения следствие перехода по имеющимся фреймам исходного изображения. Для этих целей в Java 2 ME имеются специальные методы класса Sprite. Метод nextFrame ( ) позволяет осуществить переход по^всем имеющимся фреймам исходного изображения. Как только достигается последний фрейм, то автоматически происходит переход к первому фрейму с последующим переходом по всей имеющейся последовательности, что обеспечивает цикличность анимации. Давайте рассмотрим пример использующий анимационную последовательность, изображенную на рис. 8.3. В этом примере на экран выводится изображение матроса и осуществляется цикличный переход по всем имеющимся фреймам, создавая эффект движения матроса, который с помощью семафорной азбуки передает слово «анимация».
Техника создания игр В листинге 8.3, а так же на компакт-диске в папке \Code\Listing8_3\src дается код примера иллюстрирующего работу анимационной последовательности. /**
листинг 8 . 3 класс MainGame . */ import javax.microedition.lcdui . *; import javax. microedition.midlet , *; public class MainGame extends MIDlet implements CommandListener {' ' / / команда выхода • private Command exitMidlet = new Command («Выход», Command . EXIT , СЦ ; // объект класса MyGameCanvas private MyGameCanvas mr; public void startApp() { // обрабатываем исключительную ситуацию try{ // инициализируем объект класса MyGameCanvas mr = new MyGameCanvas ( ) ; // запускаем поток mr. start ( ) ; // добавляем команду выхода mr . addCommand ( exitMidlet) ; mr .setCommandListener (this) ; // отражаем текущий дисплей Display. getDisplay (this) . setCurrent (mr) ; } catch ( java.io. lOException zxz) { } ; public void pauseApp ( ) {} public void destroyApp (boolean unconditional) { // останавливаем поток if.(mr != null) mr.stopO; public void commandAct ion (Command c, Displayable d)
Анимация в игровом процессе if (с == exitMidlet)
destroy App( false) ; notifyDestroyed ( ) ;
/** . файл MyGameCanvas . j ava класс MyGameCanvas */
i
v
import java.io.*; import javax. microedit ion. Icdui . *; import javax .microedition . Icdui . game . * ; public class MyGameCanvas extends GameCanvas implements Runnable
{ // создаем объект класса MySprite private Matros matros; // создаем /объект класса LayerManager private LayerManager 1m; // логическая переменная boolean z; public MyGameCanvas () throws lOException { // обращаемся к конструктору суперкласса Canvas super (true) ; // загружаем изображение Image im = Image. createlmage («/matros. png») ; // инициализируем объект matros matros = new Matros(im, 94, 100); // выбираем позицию matros. setPositionf 30 , 30); , // инициализируем менеджер уровней 1m = new LayerManager ( ) ; // добавляем объект матроса к уровню • ' 1m . append (matros ) ; • public void start ()
Техника создания игр z = true; // создаем и запускаем поток Thread t = new Thread (this ); t .start ( ) ;
} // останавливаем поток public void stop(){ z = false; } .public .void 'run() { •' /У получаем графический контекст Graphics g = getGraphics ( ) ; while (z) { / / рисуем графические элементы init (g) ; // останавливаем цикл try { Thread. sleep (250 ); } catch (Java. lang. InterruptedException zxz) {}
private void init (Graphics g) { // белый цвет фона g.setColor(Oxffffff ) ; // перерисовываем экран . g.fillRect (0, 0, getWidthO, getHeight ( ) ) ; // рисуем уровень в точке 0,0 1m. paint (g, 0 , 0) ; // рисуем анимацию matros .Animation ( } ; // двойная буферизация f lushGraphics ( ) ;
' /**
' . .
файл Matros.Java класс Matros */ • import javax.microedition.Icdui.*;
Анимация в игровом процессе import jayax.microedition. Icdui .game . * ; / public class Matros extends Sprite { / / конструктор public Matros (Image image, int-fw, int fh) { // обращаемся к конструктору суперкласса super (image, fw, fh) ; } У/ метод осуществляющий анимацию public void Animation () { // вызыйаем следующий фрейм next Frame ( ) ;
В листинге 8.3 нам интересно несколько моментов. В классе Matros, являющимся подклассом класса Sprite, создается метод Animation ( ) , который выглядит следующим образом: public void Animation ( ) { next Frame ( ) ; } Метод Animation ( ) осуществляет тот самый последовательный переход по имеющимся фреймам исходного изображения. В классе MyGameCanvas происходит создание объекта класса Matros: private Matros matros; Затем в конструкторе класса MyGameCanvas загружается изображение матроса и инициализируется объект matros. Image im = Image. createlmage («/matros .png») ; matros '= new Matros (im, 9 4 , 1 0 0 ) ; Размер одного фрейма с матросом равен 94x100 пикселей, поэтому указывается размер именно одного фрейма. По умолчанию загружается самый первый фрейм изображения, но можно использовать метод setFrame ( ) для установки необходимого фрейма из анимационной последовательности. В методе Graphics ( ) класса MyGameCanvas происходит вызов метода Animation ( ) : matros .Animation ( ) ; Это в ито'ге приводит к цикличному перебору всех имеющихся фреймов. Откомпилируйте код из листинга 8.3 и посмотрите работу этого примера. На экране телефона матрос с помощью семафорной азбуки передает слово «анимация».
Техника создания игр
8.9. Столкновение объектов Практически во всех играх приходится обрабатывать события связанные со столкновением двух объектов или с препятствием. В профиле MIDP 2.0 существует три отличных метода, отслеживающих факт столкновения. Все три метода определены в классе Sprite. Q collidesWith(Image image,' int x, int y , Boolean pixelLevel) - определяет факт столкновения со статическим изображением; Q collidesWith{ Sprite s, Boolean pixelLevel) - определяет столкновение между двумя объектами класса Sprite; Q collidesWith(TiledLayer t, Boolean pixelLevel) -отслеживает столкновение между объектом класса Sprite и объектом класса TiledLayer. Используя эти методы можно обрабатывать всевозможные ситуации, связанные со столкновением. Как правило, при столкновении должны произойти какие-то события, чаще всего связанные с изменением первоначального состояния объекта. Это может быть уничтожение объекта, его перемещение, уменьшение или увеличение. В основе изменения состояния объекта положен перебор имеющихся фреймов в анимационной последовательности или перерисовка изображения на новом месте. Для этих операций в классе Sprite имеется несколько методов. С одним из методов nextFrame ( ) , вы уже познакомились в разделе 8.8, рассмотрим оставшиеся методы. Q prevFrame () - с помощью этого метода происходит переход к предыдущим фреймам изображения. Этот метод подобен методу nextFrame { ) , только переход осуществляется в обратном порядке; Q setFrameO - производит установку при помощи индекса заданного фрейма из всей имеющейся последовательности фреймов. Q setFrameSequence {) - устанавливает определенную фреймовую последовательность при помощи массива индексов в анимационной последовательности; О getFrame ( ) - узнает, какой из фреймов исходного изображения используется в текущий момент; Q set Image (). - заменяет исходное изображение на новое. Можно использовать этот метод, например в том случае, если объект уничтожен, и его необходимо перерисовать заново. Набора этих методов вполне достаточно для обработки различных ситуаций возникающих в игровом процессе. Однако необходимо очень тщательно разобраться в действии всех вышеперечисленных методов. Для этого был написан исходный код примера, иллюстрирующего работу методов nextFrame ( ) , prevFrame ( ) , setFrame ( ) и setFrameSequence ( ) . В этой программе на экран выводятся четыре бомбы и синий шарик, перемещая который в разные стороны можно произвести столкновение с четырьмя бомбами. Все бомбы являются объектами класса MySprite, являющимся подклассом класса Sprite. Метод, обрабатывающий столкновение мяча и бомбы, использует один из четырех мето-
Столкновение объектов дов nextFrame ( ) , prevFrame ( ) , setFrame ( ) и setFrame'Seguence () для каждой из бомб, что красочно иллюстрирует работу каждого метода. Исходные изображения бомбы и мяча выполнены в виде последовательности четырех фреймов размером 23x23 пикселя. Первый фрейм мяча и бомбы является исходным изображением, а три последующих фрейма реализованы в виде взрыва. Переход по этим фреймам создает иллюзию взрыва мячика или бомбы. Но оттого, что для каждой бомбы как мы договорились, используются различные методы, то результат может оказаться неожиданным. Поэтому внимательно посмотрите на код примера в листинге 8.4 и запустите программу с компакт-диска \Code\ Listing8_4\bin\Listing8_4.jad с помощью любого эмулятора, поддерживающего профиль MIDP 2.0. Либо откомпилируйте исходный код из листинга 8.4 (он так же находится на компакт-диске в папке \Code\Listing8_4\src) и внимательно ознакомьтесь с работой этой программы. Я уверен, что вы без труда разберетесь, что именно нужно сделать для логического завершения взрывов бомб и мяча. Алгоритм действий очень прост и может быть следующим после столкновения мяча с одной из мин. Необходимо произвести взрыв, последовательно переходя по всем фреймам, после чего, например, нарисовать бомбу и мячик заново. В листинг 8.4 предложен исходный код примера. /** листинг 8.4 класс MainGame
*/
import javax.microedition.Icdui.*; import javax.microedition.midiet.*; public class MainGame extends MIDlet implements CommandListener
{ // команда выхода private Command exitMidlet = new Command(«Выход», Command.EXIT, 0); // объект класса MyGameCanvas private MyGameCanvas mr; public void startAppO
<{ //
обрабатываем исключительную ситуацию
try{ // инициализируем объект класса MyGameCanvas mr = new MyGameCanvas(); // запускаем поток mr.start() ; // добавляем команду выхода
Техника создания игр mr . addCoimand ( exitMidlet ) ; mr .setcommandListener (this) ; /У отражаем текущий дисплей Display .getDisplay (this) .setCurrent (mr) ; •} catch (Java. io. lOExcept ion zxz) { } ;
public void pauseAppO {} public void destroyApp (boolean unconditional) { // останавливаем поток if(mr != null) mr.stopO;
public void comm'andAct ion (Command c, Displayable d) { if (c == exitMidlet) { destroyApp (false) ; notifyDestroyed( ) ;
/** файл MyGameCanvas . j ava класс MyGameCanvas */
import java.io. * ; import javax.microedition. Icdui . *; import javax.microedition. Icdui .game. * ; public class MyGameCanvas extends GameCanvas implements Runnable { // создаем объект класса MySprite private MySprite bol ; // создаем объект класса LayerManager private LayerManager 1m; // создаем бомбы private MySprite bombal , bomba2 , ЬощЬаЗ , bomba4; // логическая переменная boolean z;
Столкновение объектов public MyGameCanvas() throws lOException •// обращаемся к конструктору суперкласса Canvas super(true); // загружаем изображение мяча Image bollmage = Image.createlmage(«/bol.png»); // инициалтзируем объект bol bol = new MySprite(bollmage, 23, 23); // выбираем позицию в центре экрана bol.setPosition(getwidth()/2, getHeightО/2); // загрузка изображения бомбы , Image bombalmage = Image.createlmage(«/bomba.png»); // инициализируем первую бомбу bombal = new MySprite"(bombaImage, 23, 23); // выбираем позицию для первой бомбы bombal.setPosition(10, 10); // инициализируем вторую бомбу bomba2 = new MySprite(bombalmage, 23, 23); // выбираем позицию для второй бомбы bomba2.setPosition( getwidth()-30, 10); // инициализируем третью бомбу ЬотЬаЗ = new MySprite(bombalmage, 23, 23),•• // выбираем позицию для третьей бомбы ЬотЬаЗ . setPosition (10 , getHeight () -4-0) ; // инициализируем четвертую бомбу bomba4 = new MySprite(bombalmage, 23, 23); // выбираем позицию для че'твертой бомбы bomba4.setPosition(getwidth()-30, getHeight()-40); // инициализируем менеджер уровней 1m = new LayerManager(); // добавляем мяч к уровню 1т.append(bol); // добавляем бомбы к уровню 1т.append(bombal); 1т.append(bomba2); 1т.append(ЬотЬаЗ); 1т. append (bomba4) ,// обрабатываем столкновение public void stolknovenie() // столкновение с первой бомбой if(bol.collidesWith(bombal, true))
Техника создания игр bol . next Frame ( ) ; bombal . nextFrame ( ) ; .
} ••// столкновение со второй бомбой if (bol .collideswith (bomba2 , true)) { bol .prevFrame ( ) ; bomba2 . prevFrame ( ) ; } // столкновение с третьей бомбой if (bol .collideswith (ЬотЬаЗ , true) )' { bol .setFrame (2) ; ЬотЬаЗ . setFrame ( 0 ) ; } // столкновение с четвертой бомбой if (bol .collideswith (bomba4 , true) ) { int[] i = {2,3};
bol . setFrame ( 0 ) ; bomba4 . setFrameSequence ( i ) ;
public void start () { z = true; // создаем и запускаем поток Thread t = new Thread(this) ; t. start () ; } // останавливаем поток' public void stop(){ z = false; } public void run() { // получаем графический контекст Graphics g = getGraphics ( ) ; • while (z) { // столкновение с препятствием stolknovenie ( ) ; // обрабатываем события с клавиш телефона input Key ( ) ;
Столкновение объектов
HIIIHH
\
// рисуем графические элементы init(g) ; // останавливаем цикл на 20 миллисекунд try { Thread. sleep (20 ) ; } catch (Java. lang. InterruptedExcept ion zxz) { } ;
private void inputKey ( ) { // определяем нажатую клавишу int keyStates = getKeyStates ( ) ; // код обработки для левой нажатой клавиши if ((keyStates & LEFT_PRESSED) != 0) bol.moveLeft ( ) ; // код обработки для правой нажатой клавиши if ((keyStates & RIGHT_PRESSED) != 0) bol .moveRight ( ) ; // код обработки для клавиши вверх if ((keyStates & UP_PRESSED) != 0) bol'.moveUp ( ) ; // код обработки для клавиши вниз if ((keyStates & DOWN_PRESSED) != 0) bol .moveDown( ) ;
>
I • I
•
.
private void init (Graphics g) { 7/ желтый цвет фона g.setColor(OxffffOO) ; , // перерисовываем экран g.fillRect (0, 0, getWidthO, getHeight ( ) ) ; // рисем уровень в точке 0 , О 1m. paint (g, 0, 0) ; х // двойная буферизация f lushGraphics ( ) ;
/** файл MySprite . j ava класс MySprite */ import javax.microedition. Icdui . *; import javax.microedition. Icdui .game. *; public class MySprite extends Sprite -
• • •
Техника создания игр // конструктор public MySprite(Image image, int fw, int fh) { // обращаемся к конструктору суперкласса super(image, fw, fh) ; } // метод для левой нажатой клавиши public void moveLeft() { // передвигаем спрайт move (-1,0) ,} // метод для правой нажатой клавиши public void moveRight() { // передвигаем спрайт move(1,0); } // метод для клавиши вверх public void moveUp() { // передвигаем спрайт move(0,-1); } // метод для клавиши вниз public void moveDown() { // передвигаем спрайт move(0,1); } Г
х
В листинге 8.4 содержатся три класса MainGame, MyGameCanvas и MySprite. Основной код обработки столкновений бомб и мяча находится в классе MyGameCanvas, этому классу мы и уделим особое внимание при разборе листинга. В конструкторе класса MyGameCanvas происходит загрузка изображения мяча из файла ресурса bol.png, инициализация объекта bol, класса MySprite и устанавливается позиция прорисовки на экране объекта bol. Image bollmage = Image.createlmage («/bol .png») ,bol = new MySprite(bollmage, 23, 2 3 ) ; bol. setPosition(getWidth ( ) /2 , getHeight ( ) / 2 ) ,-
Столкновение объектов
11111НВ1Н1ЕЕ£1
Заметьте, что позиция вывода мяча на экран установлена в центре экрана, но эта позиция определена для левой верхней точки мяча, поэтому именно левый верхний угол изображения спрайта мяча будет находиться в центре экрана. Для того чтобы нарисовать сам спрайт в центре экрана, нужно переопределить опорную позицию мяча с помощью метода def ineRef erencePixel ( ) . Затем в конструкторе класса MyGame'Canvas загружается изображение бомбы. Image bombalmage = Image.createlmage(«/bomba.png»); После этого происходит инициализация четырех объектов bombal, bomba2, ЬотЬаЗ и bomba4 класса MySprite и устанавливается позиция для вывода всех четырех бомб на экран телефона. bombal = new MySprite(bombalmage, 23, 2 3 ) ; bombal.setPosition{10, 1 0 ) ; bomba2 = new MySprite(bombalmage, 23, 2 3 ) ; bomba2.setPosition( g e t w i d t h ( ) - 3 0 , 1 0 ) ; ЬотЬаЗ = new MySprite(bombalmage, 23, 2 3 ) ; ЬотЬаЗ.setPosition(10, g e t H e i g h t ( ) - 4 0 ) ; bomba4 = new MySprite(bombalmage, 23, 2 3 ) ; bomba4 . set Posit ion (getWidth ( ) -30 , getHeight ( ) -40) ,Все четыре бомбы рисуются в разных углах экрана слева направо и сверху вниз. Произведя загрузку необходимых изображений и инициализируя все объекты класса MySprite, можно добавить их к уровню с помощью менеджера уровней. 1m.append(bo1) ; 1т. append (bombal) ,1т.append(bomba2); 1m.append(ЬотЬаЗ); 1m. append(bomba4); Наша задача в этом примере - это определение столкновения бомб и мячика, для этого создан метод stolknovenie ( ) , где при помощи конструкции if/ else происходит обработка столкновения объектов bol и bombal-bomba4. Сейчас было бы очень хорошо, если бы вы могли запустить с компакт-диска программу из листинга 8.4, она находится в папке \Code\Listing8_4\bin\Listing8_4.jad и попробовали осуществить столкновение мяча с четырьмя бомбами. Как мы договорились, при столкновении будет обсуждаться работа четырех разных методов. В столкновении с первой бомбой, находящейся в левом верхнем углу экрана, используется метод next Frame ( ) . Если вы переместите мячик по экрану, то при наезде на первую бомбу произойдет взрыв бомбы и мяча. То есть начнется перебор всех имеющихся фреймов обоих объектов в цикличном порядке. Как только вы уберете мячик с бомбы, взрыв обоих объектов прекратится, потому что закончится перебор фреймов изображений. А состояние бомбы и мяча будет соответствовать одному из фреймов всей анимационной последовательности, при
Техника создания игр этом возможности повлиять на остановку перехода по фреймам в методе nextFrame ( ) нет. Вторая бомба, находящаяся в правом верхнем углу экрана, при обработке (, столкновения использует практически идентичный предыдущему метод prevFrame ( ) , отличающийся лишь тем, что переход по всем существующим фреймам бомбы и мяча происходит в обратном порядке. Остановить работу метода на нужном фрейме также невозможно. Третья бомба рисуется в нижнем углу экрана и для обработки столкновения мяча с бомбой используется метод set Frame ( ) . Этот метод производит переход по заданным фреймам всей анимационной последовательности по номеру или индексу фрейма. В этом примере используется следующий код при столкновении мяча и третьей бомбы. bol.setFrame(2); ЬотЬаЗ.setFrame(0); Когда вы передвинете мячик на третью бомбу, то увидите, что изображение мячика изменится, и будет соответствовать третьему фрейму всей анимационной последовательности мячика. Состояние бомбы останется неизменным, потому что используется индекс 0", а это первый фрейм бомбы. Четвертая бомба при столкновении задействует метод setFrameSequenсе ( ) , благодаря которому можно использовать фреймовые последовательности в виде массива индексов. Используя эти методы, я думаю, вы вполне сможете создать любую цепочку событий для перемещения, столкновения и других возможных действий объекта. В следующей главе будет рассматриваться мультимедийная библиотека, необходимая для создания звукового сопровождения в играх.
Глава 9. Мобильная мультимедиа-библиотека Воспроизведение звуков в играх создает более насыщенную атмосферу. Хорошая звуковая дорожка к игре - это 30-40% успеха! Но, к сожалению, в мобильных играх, нет возможности воспроизведения мощной полноценной звуковой дорожки, как в компьютерных или приставочных играх, в виду ограничения системных ресурсов телефона. Поэтому, в основном, все звучание в играх сводится к воспроизведению так называемых тональных звуков. Каждый тональный звук соответствует определенной ноте, выстроив необходимую последовательность нот для воспроизведения можно получить определенную звуковую дорожку. В профиле MIDP 1.0 возможность работы со звуком отсутствует, и все строится на использовании классов, предоставляемых производителями мобильных телефонов. В профиле MIDP 2.0 такая возможность имеется, поскольку появилась мобильная мультимедиа библиотека (MMAPI), разработаная экспертной группой, в состав которой входят известные компании: Q Nokia (Specification Lead); Q Aplix Corporation; Q Beatnik, Inc.; Q France Telecom; Q Insignia Solutions; Q Mitsubishi Electric Corp.; ' Q Motorola; Q Netdecisions Holdings United; Q NTT DoCoMo, Inc.; Q Openwave Systems Inc.; Q Packet Video Corporation; a Philips; Q Siemens AGICM MP TI; Q Smart Fusion; Q Sun Microsystems, Inc.; Q Symbian Ltd; Q Texas Instruments Inc.; Q Vodafone; Q Yamaha Corporation; Q Zucotto Wireless. На данный момент существуют две мобильные мультимедиа-библиотеки, различающиеся по своему назначению и спецификации, это:
f
Мобильная мультимедиа-библиотека
О Mobile Media API - предназначена для работы с устройствами имеющими боле мощные системные ресурсы. Это, как правило, карманные портативные устройства; Q MIDP 2.0 Media API - эта библиотека направлена на поддержку мобильных устройств с ограниченными ресурсами. В этой главе будет представлена мобильная мультимедиа библиотека MIDP 2.0 Media API, которая используется при программировании звука в приложениях написанных под профиль MIDP 2.O. Работа со звуком строится по принципу блочной конструкции состоящей из трех ключевых блоков: О Менеджер - это основной диспетчер, при помощи которого создаются все проигрыватели. Также менеджер имеет возможность в воспроизведении простых тональных звуков на телефоне. Менеджер в профиле MIDP 2.0 представлен классом Manager; Q Проигрыватель - осуществляет непосредственное воспроизведение звуков и представлен интерфейсом Player; Все взаимодействие построено на использовании нескольких интерфейсов и класса Manager, содержащихся в библиотеке MIDP 2.0 Media API, которая состоит из двух пакетов: Q javax.microedition.media; Q javax.microedition.media.control. Эти два пакета содержат ряд интерфейсов и всего один класс Manager. Рассмотрим подробно оба пакета библиотеки MIDP 2.0 Media API, давая попутно краткую характеристику каждому интерфейсу, классу Manager и всем имеющимся методам. А потом, на основе полученного материала, создадим несколько примеров исходного кода, иллюстрирующих модель работы со звуком.
9.1. Пакет javax.microedition.media Пакет javax.microedition.med.ia необходим для работы со звуком и содержит четыре основных интерфейса и один класс, на базе которых и происходит воспроизведение звуков в телефоне.
9.1.1. Интерфейс Control Интерфейс Control - это самый главный интерфейс, с его помощью осуществляется контроль над всеми имеющимися ресурсами, также от этого интерфейса наследуются еще два интерфейса ToneControl и VolumeControl.
9.1.2. Интерфейс Controllable С помощью интерфейса Controllable можно получить управление над воспроизведением, посредством использования двух методов: Q Control getControl (String controlType) - определяет тип управления; Q Control [ ] getControls ( ) - получает управление.
Пакет javax.microedition.media
9.1.3. Интерфейс Player Интерфейс Player наследуется от интерфейса Controllable и необходим для реализации процесса воспроизведения звуковых данных на основе формирования проигрывателей. Проигрыватели создаются методом createPlayer { ) класса Manager, например: Player playerl = Manager.createPlayer(); После создания проигрывателя можно производить воспроизведения звука, для этого необходимо воспользоваться методами интерфейса Player.
Методы интерфейса Player Q void addPlayerListener (PlayerListener playerListener') осуществляет обработку событий от определенного проигрывателя; Q void c l o s e t ) - закрывает проигрыватель; Q void deallocate () - освобождает ресурс, занятый проигрывателем; Q String getContentType ( ) - получает тип звуковых данных воспроизводимых проигрывателем; Q long getDuration() - получает размер звукового файла; Q long getMediaTime ( ) — получает время воспроизведения звуковых данных; Q int g e t s t a t e ( ) — определяет состояние проигрывателя; G void removePlayerListener(PlayerListener playerListener) - удаляет установленный обработчик событий; Q void setLoopCount (int count) - устанавливает цикличное воспроизведение звуковых данных; О long setMediaTimedong now) - устанавливает время воспроизведения; О void start ( ) - дает команду на воспроизведение; Q void stop ( ) - останавливает воспроизведение. Большинство методов направленно на работу со звуковыми данными, позже в разделе 9.3 мы разберем подробнее работу с методами интерфейса Player.
9.1.4. Интерфейс PlayerListener Интерфейс PlayerListener позволяет осуществлять обработку событий полученных от проигрывателя. Помните в главе 5 мы разбирали работу интерфейса CommandListener? Интерфейс PlayerListener функционирует почти по такой же схеме, но ориентирован на работу с проигрывателем. В составе интерфейса PlayerListener имеется всего один метод: Q void playerUpdate(Player player, String event, Object eventData) - обновляет состояние проигрывателя. С помощью констант интерфейса Player в методе playerUpdate ( ) , нужно задавать тип необходимых событий в параметрах eventData и event: Q static String CLOSED - уведомляет о закрытии проигрывателя;
Мобильная мультимедиа-библиотека Q static String DEVICE_AVAILABLE - уведомляет о доступности проигрывателя; О static String DEVICE_UNAVAILABLE - уведомляет о недоступности проигрывателя; О "static String DURATION_UPDATED - обновляет состояние; Q static String END_OF_MEDIA - уведомляет о конце воспроизведения данных проигрывателем; Q static String ERROR - уведомляет об ошибке; О static String STARTED - уведомляет о начале работы проигрывателя; Q static String STOPPED - уведомляет о конце работы проигрывателя; Q static String VOLUME_CHANGED - уведомляет о выборе громкости для воспроизведения.
9.1.5. Класс Manager Класс Manager создает проигрыватель для воспроизведения звуков, а также отслеживает доступные протоколы звуковых данных, с помощью нескольких методов. О static Player createPlayer(InputStream stream, String type) - создает проигрыватель для воспроизведения звуковых данных из потока; Q s t a t i c Player createPlayer(String locator) - создает проигрыватель для воспроизведения звуковых данных из определенного файла; D static String[] getSupportedProtocols(String content_type) - возвращает список доступных протоколов для мобильного устройства; Q static void playTone(int note, int duration, int volume) — воспроизводит различные тональные звуки.
9.2. Пакет javax.microedition.media.control Пакет javox.microedition.media.control небольшой по своему составу и производит контроль над процессами, связанными с воспроизведением и регулировкой звука. В разделе 9.4 этой главы очень подробно рассматривается схема контроля.
9.2.1. Интерфейс ToneControl С помощью интерфейса ToneControl происходит настройка и построение блока тональных звуков для воспроизведения. Это достигается путем использования метода void setSequence (byte [ ] sequence), который устанавливает тональные звуки для воспроизведения и набора следующих констант: Q static byte BLOCK_END - конец блока воспроизведения; Q static byte BLOCK_START - стартовая позиция в блоке; Q s t a t i c byte C4 - нота До; Q s t a t i c byte PLAY_BLOCK - воспроизвести блок; О static byte REPEAT - повторить воспроизведение блока;
Воспроизведение wav-файлов Q static byte SET_VOLUME - установить громкость; Q static byte SILENCE - без звука; Q static byte TEMPO - темп или скорость воспроизведения; Q static byte VERSION - версия атрибута воспроизведения. С помощью перечисленных констант производится настройка блока тональных звуков для воспроизведения, о которых мы поговорим подробно в разделе 9.4.
9.2.2. Интерфейс VolumeControl Интерфейс VolumeControl имеет методы, на основе которых можно реализовать управление громкостью воспроизведения: Q int getLevel ( ) - возвращает текущий уровень громкости; О boolean isMutedO - определяет состояние сигнала; О int setLevel (int level) - устанавливает уровень громкости. Значение может находиться в пределах от 0 до 100; Q void setMute (boolean mute) - устанавливает состояние сигнала. Сейчас мы вкратце рассмотрели имеющиеся интерфейсы, классы, методы и константы двух пакетов javax.microedition.media и javax.microedition.niedia.control. Теперь давайте подытожим все полученную информацию и рассмотрим примеры, иллюстрирующие работу со звуком в мобильных телефонах.
9.3. Воспроизведение wav-файлов Воспроизведение wav-файлов в телефоне задача не сложная. Wav-файл .должен быть размещен в каталоге создаваемого приложения. Если вы' используете J2ME Wireless Toolkit 2.1, то расположите wav-файл в папке res. Впоследствии, после компиляции и установки программы, wav-файл будет находиться в J ARархиве, и доступен для воспроизведения. Для того чтобы воспроизвести необходимый wav-файл создается объект класса InputStream для связывания потока данных с ресурсом, а именно wavфайлом, например: InputStream input = getClass ( ) . getResourceAsStream(<«£ai«i .wav») ; Затем создается проигрыватель: Player player = Manager.createPlayer(input,' «audio/X-wav»); Проигрыватель формируется с помощью метода createPlayerQ класса Manager. Количество создаваемых проигрывателей регламентируется только системными ресурсами телефона. После чего используется метод startQ для воспроизведения wav-файла. В листинге 9.1 вы найдете пример исходного кода, в котором происходит загрузка и воспроизведение wav-файла из JAR-архива. В примере используется класс Form, с помощью которого создается пустой экран, и добавляются две ко-
Мобильная мультимедиа-библиотека манды: выход из приложения и воспроизведение wav-файла. Основные действия разворачиваются в методе WavPIay ( ) , где создается проигрыватель и воспроизводится wav-файл. Обратите также внимание на подключаемые пакеты.
/** листинг 9 . 1 класс WavMIDlet /' воспроизводит wav-файл */ import javax.microedition. Icdui . * ; import javax.microedition.midlet . * ; import javax.microedition. media. *; import javax.microeditionlmedia. control . * ; import java.io.*; public class WavMIDlet extends MIDlqt implements CommandListener { / / команда выхода private Command exitMidlet = new Command ( "Выход" , Command . EXIT , 0 ) ; // команда воспроизведения private Command pi' = new Command ( "Играть" , Command. OK, 1) ; // объект mydisplay представляет экрай телефона private Display mydisplay; public WavMIDlet ( ) { mydisplay = Display .getDisplay (this) ; public void startApp ( ) { Form Is = new Form ( "Воспроизведение wav"); // добавляем команду выхода Is . addCommand ( exitMidlet) ; //. добавляем команду воспроизведения Is .addCommand (pi) ; Is . setCornmandListener (this) ; // отражаем текущий дисплей mydisplay .setCurrent (Is) ; private void WawPlay(
Воспроизведение тональных звуков try { // ищем ресурс с именем melod.wav InputStream input = getClassO.getResourceAsStream("melod.wav"); // создаем проигрыватель Player player = Manager.createPlayer(input, "audio/X-wav"); // воспроизводим player.start(); } catch (lOException zxz) {} catch (MediaException zmz) {} }
public void pauseAppO {} public void destroyApp(boolean unconditional){} public void commandAction(Command c, Displayable d) if (c == exitMidlet) destroyApp(false); notifyDestroyed();
. .
if (c == pi)
WawPlay();
9.4. Воспроизведение тональных звуков При создании звукового сопровождения к играм и приложениям в основном используются так называемые тональные звуки, генерируемые телефоном. Мобильные телефоны ограничены в системных ресурсах, поэтому воспроизведение wav, mp3 файлов не всегда возможно. Воспроизведение тональных звуков происходит примерно тем же способом, что и воспроизведение wav-файлов, рассмотренное в предыдущем разделе. Создание тональных звуков строится на основе секвенсора, используемого музыкантами. То есть, в вашем распоряжении имеются семь нот, которые могут быть сыграны в любой тональности. Указав определенную последовательность нот в Заданном массиве данных, вы сможете их впоследствии последовательно воспроизвести. В принципе, аналогичные действия можно произвести в любом те-
Мобильная мультимедиа-библиотека лефоне, где в музыкальном редакторе вы выстраиваете некую последовательность определенных символов, обозначающих ноты. Указав нужную последовательность нот, вы получаете готовую мелодию, созданную при помощи тональных звуков. Перейдем к практике. Первым делом необходимо создать те самые семь нот. В классе ToneControl пакета javax.microedition.media.control.*, доступна константа С4, которая по своему звучанию соответствует ноте «До». Для того чтобы создать, например ноту Ре, можно воспользоваться следующей конструкцией кода: byte Re = (byte)(ToneControl.C4+1); Для создания последующей ноты Ми нужно прибавить к ноте До (то есть С4), число два и так далее. Когда закончатся все семь нот, то вы переходите к следующей октаве, что и предопределяет разные тональности звукового сопровождения. Всего можно использовать значение от 0 до 127. Затем создается массив данных, можно назвать его секвенсором, в котором указывается последовательность нот. Синтаксис, используемый в секвенсоре, строго определен, и его необходимо правильно использовать. Например, имеется следующий массив данных, характеризующийся как секвенсор: byte[] Nota = {...}; В этом массиве данных первой строкой кода должно идти указание версии используемого атрибута. ToneControl.VERSION, I,
Затем задается скорость воспроизведения с помощью целочисленного значения, которое может варьироваться от 5 до 127. Например: ToneControl.TEMPO, 30, Далее необходимо дать команду, указывающую начало блока последовательности нот для воспроизведения, например: ToneControl.BLOCK_START, 0, И только после этого идет последовательность нот. Между нотами ставится обязательно длина ноты обычно заданная переменной, и ее диапазон может быть от 2 до 16. Например: byte d = 4,Re,d,Mi,d,Re,d, Между воспроизведением нот можно использовать паузы для создания выразительной мелодии. Пауза задается с помощью константы SELENCE, например: byte stop = ToneControl.SELENCE,• byte d = 4; Тогда последовательность нот может быть следующей:
Воспроизведение тональных звуков R e , d , stop, d, Mi ,d, stop,d, s t o p , d , R e , d , , '> ' После того как вы задали всю последовательность нот, необходимо четко указать конец блока с помощью константы BLOCKJ.END следующим образом: ToneControl . BLOCK_END , 0 ,
На каждую константу BLOCK_START, должна присутствовать константа BLOCK_END. Иначе возникнет ошибка при компиляции. В конце нужно воспользоваться константой PLAY_BLOCK для воспроизведения блока последовательности нот. После этого созданный секвенсор можно использовать для воспроизведения проигрывателем тональных звуков. Посмотрите на листинг 9.2, где показана демонстрационная программа, воспроизводящая все семь нот одной октавы. /•** листинг 9 . 2 класс TonMIDlet' воспроизводит тональные звуки
*/ import javax.microedition. Icdui . * ; import javax.microedition. midlet . * ; import javax.microedition. media . * ; import javax.microedition. media. control . *; import j ava . io . * ; public class TonMIDlet extends MID'let implements CommandListener { // команда выхода private Command exitMidlet = new Command ( "Выход" , Command . EXIT , 0) ; // команда воспроизведения private Command pi = new Command ( "Играть" , Command. OK, 1) ; // объект mydisplay представляет экран телефона private Display mydisplay; public 'TonMIDlet ( ) { mydisplay = Display .getDisplay (this) ;
public void startApp() { Form Is = new Form ( "Тональные звуки"); / / добавляем команду выхода
•
Мобильная мультимедиа-библиотека Is . addCoitimand(exitMidlet) ; // добавляем команду^ воспроизведения Is.addCommand(pl) ; Is , setCommandListener (this) ; / / отражаем текущий дисплей my display . set Current (Is) .,-
private void TonPlayO { // нота До byte Do = ToneControl . C4; // нота Ре byte Re = (byte) (ToneControl .C4 + 1) ,// нота Ми . byte Mi = (byte) (ToneControl .C4 + 2); // нота Фа byte Fa = (byte) (ToneControl. C4 + 3); // нота Соль byte So = (byte) (ToneControl .C4 + 4) ; / / нота Ля byte Lj = (byte) (ToneControl. C4 +' 5) ,// нота Си byte Si = (byte) (ToneControl .C4 + 6) ; // пауза byte stop = ToneControl .SILENCE; // скорость воспроизведения тональных звуков byte speed = 30; // продолжительность воспроизведения ноты byte pr = 4; // секвенсор byte[] Nota = { // атрибут, задающий номер версии ToneControl. VERSION, I, // скорость воспроизведения ToneControl .TEMPO, speed, // начало блока ToneControl. BLOCK_START, 0, // последовательность нот для воспроизведения Do , pr ,- stop , pr , Re , pr , stop , pr , Mi , pr , stop , pr , Fa,pr , stop,pr , So,pr , stop,pr ,Lj ,pr ,stop,pr , Si ,pr , // конец блока ToneControl. BLOCK_END, 0, // воспроизведение' блока
Воспроизведение тональных звуков ToneControl . PLAY_BLOCK , 0 , }; // воспроизводим тональные звуки из секвенсора try{ Player player = Manager. createPlayer (Manager. TONE_DEVICE_LOCATOR) ; player .realize (); . ToneControl toncontrl = ( ToneControl) player .getControl («ToneControl») ; toncontrl . setSequence (Nota) ; player. start ( ) ; } catch (lOException zxz){} catch (MediaException zmz){} } public void pauseAppO {} public void destroy App (boolean unconditional) {} public void commandAct ion (Command c, Displayable d) { if (c == exitMidlet) { destroy App ( false) ;, notifyDestroyed( ) ; } if (c == pi) { TonPlay ( ) ;
В основе программы из листинга 9.2 лежит модель, используемая в предыдущем разделе при воспроизведении wav-файла. В классе TonMIDlet создается пустая форма классом Form и назначаются две команды: выход из программы и воспроизведение тональных звуков. При нажатии на кнопку Играть, задействуется метод TonPlay ( ) , где создаются ноты, секвенсор, после чего происходит воспроизведение последовательности нот.
•I Заключение Технология Java 2 Micro Edition предоставляет разработчику программного обеспечения широкий спектр хорошо продуманных интерфейсов, классов, методов и констант, на основе которых происходит построение приложений для телефонов, КПК, телевизионных приставок, органайзеров, пейджеров и других мобильных устройств. Платформа Java 2 Micro Edition - это стандарт программирования мобильных телефонов, признанный такими известнейшими компаниями как Nokia, Siemens, Sony Ericsson, Motorola, Samsung, Symbian, Palm Computing, Sharp, Mitsubishi, NEC и так далее. В книге вы изучили практически все компоненты платформы Java 2 Micro Edition, за исключением ряда специфических свойств, ознакомиться с которыми можно с помощью справочника, находящегося в приложении 2 этой книги. Как автор, надеюсь, что эта книга помогла вам разобраться в хитростях технологии Java 2 Micro Edition и поможет найти в дальнейшем хорошо оплачиваемую работу. При прочтении книги у вас наверно появлялись различные вопросы, задать которые можно по адресу электронной почты: [email protected]. Думаю, что количество вопросов может исчисляться сотнями, поэтому на все ответить не смогу, но на наиболее интересные вопросы отвечу обязательно.
Приложение 1. Основы языка Java Это приложение не претендует на роль полного руководства по языку Java (Ява), но данного материала будет достаточно для дальнейшего изучения книги. Предлагаемая к рассмотрению в этом разделе информация содержит основы языка Java и ориентирована на неподготовленного читателя. Также нужно иметь в виду, что обучение языку Java будет происходить в соответствии с контекстом книги, а именно, всей той части языка Java, необходимой для программирования мобильных устройств. То есть такие «продвинутые» темы как аплеты, библ-иотеки AWT и Swing в этом приложении не рассматриваются, поскольку не применяются в Java 2 Micro Edition.
1.1. Введение в программирование Программирование - это написание исходного кода программы на одном из языков программирования. Существует множество различных языков программирования, благодаря которым создаются всевозможные программы, решающие определенный круг задач. Язык программирования - это набор зарезервированных слов, с помощью которых пишется исходный код программы. Компьютерные системы еще не в силах понимать человеческий язык и логику, поэтому все программы пишутся на языках программирования, которые впоследствии переводятся на язык компьютера, то есть в машинный код. Системы, переводящие исходный код программы в машинный код, очень сложные и их, как правило, создают не один десяток месяцев и не один десяток программистов. Такие системы называются интегрированными средами программирования приложений. Система программирования представляет собой огромную продуманную визуальную среду, где можно писать исходный код программы, переводить его в машинный код, тестировать, отлаживать и многое другое. Также существуют программы, которые позволяют производить вышеперечисленные действия при помощи командной строки. Язык Java предоставляет такую возможность, но в книге данная проблематика не освещается. Вы, наверное, не раз слышали термин «программа написана под Windows или под Linux, Unix». Дело в том, что среды программирования при переводе языка программирования в машинный код могут быть двух видов - это компиляторы и интерпретаторы. Говоря про общий вид: компиляция или интерпретация программы задает способ дальнейшего выполнения программы. Программы написанные на языке Java всегда работают на основе интерпретации, тогда как программы написанные на C/C++ - компиляции. В чем разница этих двух способов? Компилятор после написания исходного кода в момент компиляции читает сразу
Основы языка Java весь исходный код программы и переводит в машинный код. После чего программа существует как одно целое и может выполняться только в той операционной системе, в которой она была написана. Поэтому программы, написанные под Windows, не могут функционировать в среде Linux и наоборот. Интерпретатор осуществляет пошаговое или построчное выполнение программы каждый раз, когда она выполняется. Во время интерпретации создается не выполняемый код, а виртуальный, который впоследствии выполняется виртуальной Java машиной. Поэтому на любой платформе - Windows или Linux, Java-программы могут одинаково выполняться при наличии в системе виртуальной Java машины, которая еще носит название Системы времени выполнения. Все что сейчас от вас требуется - это изучение синтаксиса языка Java, для того чтобы писать и понимать исходные коды программ, написанные на этом языке. А так же освоить работу с одной из сред программирования, подробное описание которых вы найдете в главе 3. Это приложение содержит теоретический материал, раскрывающий особенности программирования на языке Java.
1.2. Объектно-ориентированное программирование Java типиризированный, и по своей природе объектно-ориентированный язык программирования. Эти термины при детальном рассмотрении очень просты в понимании. Основных типов данных мы коснемся, когда будем обсуждать семантику языка, а сейчас сосредоточимся на объектно-ориентированной парадигме современного программирования. Объектно-ориентированное программирование построено на объектах по аналогии с нашим миром. Если оглянуться вокруг себя, то обязательно можно найти что-то, что поможет более ярко разобраться в модели такого программирования. Например, я сейчас сижу за столом и печатаю эту главу на компьютере, который состоит из монитора, системного блока, клавиатуры, мыши и так далее. Все эти части являются объектами/из которых состоит компьютер. Зная это, очень легко сформулировать какую-то обобщенную модель работы всего компьютера. Если не разбираться в тонкостях программных и аппаратных свойств компьютера, то можно сказать, что объект Системный блок производит определенные действия, которые показывает объект Монитор. Объект Клавиатура в свою очередь может корректировать или вообще задавать действия для объекта Системный блок, а тот влияет на объект Монитор. Объект Колонки предназначен для воспроизведения звуковых данных с различных источников. Построенный процесс очень хорошо характеризует всю систему объектно-ориентированного программирования. Представьте себе некий мощный программный продукт, содержащий сотни тысяч строк кода. Если не использовать объектно-ориентированное программирование, то вся программа должна выполняться построчно, строка за строкой и в принципе каждая из последующих строк кода обязательно будет связана с предыдущей. Когда потребуется изменить этот программный код, скажем при необходимости улучшения каких-то элементов, то придется произве-
Объектно-ориентированное
программирование
сти большое количество работы с кодом. В объектно-ориентированном программировании все куда проще. Допустим, вас уже не устраивает пятнадцати дюймовый монитор. Вы можете спокойно его обменять, например на семнадцати или девятнадцати дюймовый монитор, конечно же, при наличии определенных материальных средств. Сам же процесс обмена не повлечет за собой огромных проблем. Ну, разве что драйвер придется сменить, да вытереть пыль из-под старого монитора. Объектно-ориентированное программирование очень легко и ясно отражает суть решаемой проблемы и что самое главное, дает возможность беь ущерба для всей программы убирать старые и ненужные объекты заменяя их на новые, точнее говоря, модернизировать без лишних затрат. Также общая читабельность всей программы становится намного проще. Существенно и то, что один и тот же код можно использовать в абсолютно разных программах.
1.2.1. Классы Стержнем всех программ Java являются классы, на которых основывается объектно-ориентированное программирование. Вы по сути уже знаете, что такое классы, но пока об этом не догадываетесь. В предыдущем разделе мы говорили об объектах, ставя в пример устройство всего компьютера. Каждый объектов, из которых собран компьютер, является представителем своего класса. Например, класс Мониторов объединяет все мониторы вне зависимости от их типов, размеров и возможностей, а один какой-то конкретный монитор, стоящий на вашем столе и есть объект класса мониторов. Такой подход позволяет очень легко моделировать всевозможные процессы в программировании, облегчая решение поставленных задач. Например, имеется четыре объекта четырех разных классов: монитор, системный блок, клавиатура и колонки. Чтобы воспроизвести звуковой файл необходимо при помощи клавиатуры дать команду системному блоку, само же действие по даче команды вы будете наблюдать визуально на мониторе и, в итоге, колонки воспроизведут звуковой файл. То есть любой объект является частью определенного класса и содержит в себе все имеющиеся у этого класса средства и возможности. Объектов одного класса может быть столько, сколько это необходимо для решения поставленной задачи.
1.2.2. Методы Когда приводился пример воспроизведения звукового файла, то было упомянуто о даче команды или сообщения, на основе которого и выполнялись определенные действия. Задача по выполнению действий решается с помощью методов, которые имеет каждый объект. Методы — это набор команд, с помощью которых можно производить те или иные действия с объектом. Каждый объект имеет свое назначение и призван решать определенный круг задач с помощью методов. Какой толк был бы, например, в объекте Клавиатура, если нельзя было бы нажимать на клавиши получая при этом возможность отдавать команды? Объект Клавиатура имеет некое количество клавиш, с помощью которых пользователь приобретает контроль над устройством ввода и может от-
Основы языка Java давать необходимые команды. Обработка таких команд в целом, происходит с помощью методов. Например, вы нажимаете клавишу Esc для отмены какихлибо действий и тем самым даете команду методу, закрепленному за этой клавишей который на программном уровне решает эту задачу. Сразу же возникает вопрос о количестве методов объекта Клавиатура, но здесь может быть различная реализация — как от определения методов для каждой из клавиш (что, вообще-то, неразумно), так и до создания одного метода который будет следить за общим состоянием клавиатуры. То есть, этот метод следит за тем, была ли нажата клавиша, а потом в зависимости от того какая из клавиш задействована, решает, что ему делать. Итак, мы видим, что каждый из объектов может иметь в своем распоряжении набор методов для решения различных задач: А поскольку каждый объект явля'ется объектом определенного класса, то получается, что класс содержит набор методов, которыми и пользуются различные объекты одного класса. В языке Java все созданные вами методы должны принадлежать или являться частью какогото конкретного класса.
1 .3. Синтаксис и семантика языка Java 2 ME Для того чтобы говорить и читать на любом иностранном языке, необходимо изучить алфавит и грамматику этого языка. Подобное условие наблюдается и при изучении языков программирования, с той лишь разницей, как мне кажется, что этот процесс несколько легче. Таким образом, как вы знаете из раздела посвященного основам программирования, прежде чем начинать писать исходный код программы, необходимо сначала решить поставленную перед вами задачу в любом удобном для себя виде. Давайте создадим некий класс отвечающий, например, за телефон, который будет иметь всего два метода: включающий и выключающий этот самый телефон. Поскольку мы сейчас не знаем синтаксис языка Java, то напишем класс Телефон на абстрактном языке. Класс Телефон {. Метод Включить ( )
{ // операции по включению телефона } Метод Выключить ( )
{ / / операции по выключению телефона
Таким вот образом может выглядеть класс Телефон. Заметьте, что фигурные скобки обозначают соответственно начало и конец тела класса, метода, либо вся-
Синтаксис и семантика языка Java 2 ME
1§Н1НН11НЕЮ
кой последовательности данных. То есть скобки указывают на принадлежность к методу или классу. На каждую открывающую скобку обязательно должна быть закрывающая скобка. Чтобы не запутаться их обычно ставят на одном уровне в коде. А теперь давайте запишем тот же самый класс только уже на языке Java. class T e l e f o n { / void on ( ) {
// тело метода on ( ) } void off ( ) { // тело метода off()
Ключевое слово class в языке Java объявляет класс, далее идет название самого класса. В нашем случае это Telefon. Сразу пару слов касательно регистра записи. Почти во всех языках программирования важно сохранять запись названий в том регистре, в котором она была сделана. Если вы написали Telefon, то уже такое написание как telef on или TELef oN выдаст ошибку при компиляции. Как написали первоначально, так и надо писать дальше. Зарезервированные или ключевые слова записываются в своем определенном регистре, и вы не можете их использовать, давая их названия методам, классам, объектам и так далее. Пробелы между словами не имеют значения, поскольку компилятор их просто игнорирует, но для читабельности кода они важны. В теле класса Telefon имеются два метода: on ( ) - включающий телефон и метод of f ( ) - выключающий телефон. Оба метода имеют свои тела и в них по идее должен быть какой-то программный код, описывающий необходимые действия обоих методов. Для нас сейчас не важно как происходит реализация этих методов, первостепенное - это синтаксис языка Java. Оба метода имеют круглые скобки on ( ) , внутри которых могут быть записаны параметры, например on ( int time) или on (int time, int timel) .Спомощью параметров происходит своего рода связь методов с внешним миром. Говорят, что метод on ( int time) принимает параметр time. Для чего это нужно? Например, вы хотите, чтобы телефон включился в определенное время. Тогда целочисленное значение в параметре time будет передано в тело метода и на основе полученных данных произойдет включение телефона. Если скобки пусты, то метод не принимает никаких параметров.
1.3. 1. Комментарии В классе Telef on в телах обоих методов имеется запись после двух слешей: / /. Такая запись обозначает комментарии, которые будут игнорироваться компиля-
Основы языка Java тором, но нужны для читабельности кода. Чем больше информации вы закомментируете по ходу написания программы, тем больше у вас будет шансов вспомнить через год, что вы хотели сделать. Комментарии в Java могут быть трех видов, это: / / , /*...*/ и /**...*/. Комментарии, записанные с помощь оператора / / должны располагаться в одной строке:
// Одна строка !!! Ошибка! На вторую строку переносить нельзя! // Первая строка // Вторая'строка // ... // Последняя строка Комментарии, использующие оператор /*...*/ могут находится на нескольких строках. В начале вашего комментария поставьте /*, а в конце, когда закончите комментировать код, поставьте оператор * /. Последний вид комментария /**...*/ используется при документировании кода и также может располагаться на любом количестве строк.
1.3.2. Типы данных Java
i
•
Чтобы задать произвольное значение, в Java существуют типы данных. Как уже говорилось, Java - язык типиризированный, поэтому каждое значение имеет свой тип. В классе Telef on мы создали два метода. Оба метода не имели параметров, но когда приводился пример метода on (int t ime) с параметром t ime, говорилось о передаче значения в метод. Данное значение указывало на время, с помощью которого якобы должен включиться телефон. Спецификатор int как раз и определяет тип значения time. В Java 2 ME шесть типов данных. Посмотрите на табл. 1.1.
Таблица 1,1. Тип byte short int long char boolean
Назначение маленькое целое короткое целое целое длинное целое символ . логический тип
Размер в байтах 1 2 4 8 2
Java 2 ME в отличие от Java 2 SE не поддерживает числа с дробной частью в связи с тем, что мобильные устройства имеют небольшие по объему ресурсы. G byte — маленькое целочисленное значение от -128 до 128; D short - короткое целое значение в диапазоне от -32768 до 32767; Q int - содержит любое целочисленное значение от -2147483648 до 2147483647;
Синтаксис и семантика языка Java 2 ME Q long - очень большое целочисленное значение, от -922337203685475808 до 9223372036854775807; Q char - это символьная константа в формате Unicode. Диапазон данного формата от 0 до 65536, что равно 256 символам. Любой символ этого типа должен записываться в одинарных кавычках: 'G'; Q boolean - логический тип, имеет всего два значения: false - ложь и true истина. Этот тип часто используется в циклах о которых чуть позже. Смысл очень прост - если у вас в кармане есть деньги, предположительно это true, а если нет то false. Таким образом, если деньги имеются - идем в магазин за хлебом или пивом (нужное подчеркнуть), если нет денег остаемся дома. То есть определяется логическая величина, способствующая выбору дальнейших действий вашей программы. Чтобы объявить какое-то необходимое значение используется запись: i.nt long char
time; BigTime,word;
Оператор точка с запятой необходим после таких записей в конце строки. Можно совместить несколько одинаковых по типу объявлений через запятую: mt
time, t i m e l , time2;
Теперь давайте, усовершенствуем наш класс Telefon, добавив в него несколько значений. Методы on ( ) и off ( ) нам больше не нужны, добавим методы поинтересней. class Telefon { //S - площадь дисплея //w - высота дисплея //h - ширина дисплея int w, h, S; //метод вычисляющий площадь дисплея vord Area ( ) { S = w*h;
Итак, мы имеем три переменные S, w и h, отвечающие, соответственно, за площадь, высоту и ширину дисплея в пикселях. Метод Area ( ) вычисляет площадь экрана телефона в пикселях. Операция бесполезная, но очень показательная и простая в понимании. Тело метода Area ( ) обрело себя и имеет вид S = w*h. Мы просто перемножаем высоту на ширину и присваиваем или как еще говорят, сохраняем результат в переменной S. Сейчас мы подошли вплотную к операторам языка Java, с помощью которых можно совершать всевозможные операции.
Основы языка Java
1.3.3. Операторы Операторы языка Java имеют различные назначения. Существуют арифметические операторы, операторы инкремента и декремента, логические операторы и операторы отношения. Арифметические операторы очень просты и аналогичны операторам умножения «*», деления.«/», сложения «+» и вычитания «-» используемые в математике. Существует оператор деления по модулю «%» и слегка запутанная на первый взгляд ситуация с оператором равно «=». Оператор равно в языках программирования называется оператором присваивания: int х = 3
Здесь вы переменной х присваиваете значение 3. А оператор «равно» в языках программирования соответствует записи двух подряд операторов «равно»: «==». Рассмотрим на примере, что могут делать различные арифметические операторы. int х = У = z =
х, у, z; 5; 3; 0;
Z = X + у;
В данном случае z будет иметь значение уже суммы х и у, то есть 8. х = z*x;
Переменная х имела значение 5, но после такой записи предыдущее значение теряется и записывается произведение z *х (8*5), что равно 40. Теперь, если мы продолжим дальше наш код, то переменные будут иметь такой вид: // х = 4 0 ; // У = 3;
// . z = 8;
Это обязательно необходимо иметь в виду. Что касается оператора деления, то поскольку Java 2 ME не поддерживает дробных чисел, то результат такого деления: X = Z /у ;
что равносильно записи: х = 8/3;
будет равен 2. Дробная часть просто отбрасывается, то же самое происходит при использовании оператор деления по модулю «%». Операторы сложения и вычитания имеют те же назначения что и в математике. Отрицательные числа так же родственны.
Синтаксис и семантика языка Java 2 ME Операторы декремента « — » и инкремента «++» весьма специфичны, но очень просты. В программировании часто встречаются моменты, когда требуется увеличить или уменьшить значение на единицу. Часто это встречается в циклах. Операция инкремента увеличивает переменную на единицу. int x = 5 ;
// Здесь х уже равен 6 Операция декремента уменьшает переменную на единицу. int х = 5 ; х-;
/ / х равен 4 Операции инкремента и декремента могут быть пост и префиксными: int х = 5; int у = 0; У = х++;
,
8 последней строке кода сначала значение х присваивается у, это значение 5, и только потом переменная х увеличивается на еденицу. Получается что: х = 6, у = 5
Префиксный инкремент имеет вид: int х = 3 ; int у = 0; • у = ++х;
И в этом случае, сначала переменная х увеличивается на один, а потом присваивает уже увеличенное значение у. . у = 4, х = 4
Операторы отношения позволяют проверить равенство обеих частей выражения. Имеется оператор равенства «==», операторы меньше «<» и больше «>», меньше или равно <«'=» и больше или равно «>=», а так же оператор отрицания «!=». 9 == 10;
Это выражение не верно, девять не равно десяти, поэтому его значение этого выражения равно false. 9 •!=
10; .
Здесь же, наоборот, оператор отрицания указывает на неравенство выражения, и значение будет равно true. Операторы больше, меньше, больше или равно и меньше или равно аналогичны соответствующим операторам из математики.
Основы языка Java Существует два логических оператора. Оператор «И», обозначающийся значками «&&» и оператор «ИЛИ», обозначенный в виде двух прямых слешей «||». Например, имеется выражение: А*В && В*С;
В том случае, если только обе части выражения истинны, значение выражения считается истинным. Если одна из частей неверна, то значение всего выражения будет ложным. В противовес оператору «&&» имеется оператор « I I », не напрасно имеющий название «ИЛИ». I I
А*В
В*С;
Если любая из частей выражения истинна, то и все выражение считается истинным. Оба оператора можно комбинировать в одном выражении, например: А*В
I I
В*С && C*D
| I
В*А;
С помощью этого выражения я вас ввел, как мне кажется, в затруднение, неправда ли? Дело в том, что в Java, как и в математике существует приоритет или так называемая иерархия операторов, с помощью которой определяется какой из операторов главнее, а, следовательно, и проверяется первым. Рассмотрим с помощью списка приоритет всех операторов языка Java: [] , ., О , !, ~, ++, '- -, + (унарный), - (унарный), new, *, / , %,
< Г
<~ I
~ I.
> ,
•
/
&, л, I , &&,
11,
9. ••
•
=, /=, %=, | = , л = , «=, »=, »>=.
Не со всеми операторами вы еще знакомы, поэтому пугаться не стоит. Ассоциативность операторов в списке следует слева на право и сверху вниз. То есть все, что находится левее и выше - старше по званию и главнее.
1.3.4. Метод main Класс Telefon, который мы описывали в предыдущем разделе, имел один метод, с помощью которого вычислялась площадь дисплея. Созданная спецификация класса Telefon может быть описана как угодно. Можно добавить реагирующие на обработку событий с клавиатуры телефона и любые другие методы, которые вы сочтете нужными для описания класса Telefon. Таких, и подобных
Синтаксис и семантика языка Java 2 ME классов может быть любое количество. Каждый из классов принято хранить в своем отдельном файле с расширением *.java. Например, Telefon.java. Все методы находящиеся в классе Telef on, которые вы опишете для данного класса, обязаны производить определенные действия с объектом этого класса, иначе, зачем нужны эти методы. Реализация методов как уже говорилось, происходит непосредственно в создаваемом классе. Но возникает вопрос, где и как, происходит вызов необходимых по ситуации методов или создание объектов используемого класса. В языке Java для этих целей существует метод main ( ) , который подобно строительной площадке собирает на своей платформе по частям объекты, методы, строя при этом функциональность всей программы. .
public class. RunTelefon { public static void main( String [] args) { / / Работа программы
Пока не обращайте внимания на ключевые слова public и static - о них чуть позже. Создав класс RunTelefon и определив в его теле метод main ( ) мы теперь имеем возможность пользоваться классом Telef on и его не особо богатой функциональностью. Объединив эти два класса в один файл, либо записав каждый по отдельности, вы получите работоспособную программу. Класс Telef on содержит основные данные и методы, а класс RunTelefon берет на себя роль мотора. Внутри класса RunTelefon происходит создание объектов класса, в данном случае класса Telef on и вызовы соответствующих методов этого класса. Например: class Telefon { // переменные int w, h, s; // метод void Area ( ) { S = w*h; class RunTelefon { public static void main (String args [ ] ) { /* создание объектов и вызовы метода Area ( ) .*/
.
Основы языка Java Поскольку вы пока не умеете создавать объекты классов и вызывать методы, тело класса RunTelef on пустое. Прежде чем идти дальше, необходимо познакомиться с ключевыми словами public, private и protected, а так же научиться создавать конструкторы классов.
1.3.5. Закрытые и открытые члены классов Ключевое слово public, объявленное перед методом main ( ) , показывает на то, что метод main ( ) считается открытым или в любом классе метод main ( ) виден, и к нему можно обратиться. Ключевое слово public может назначаться не только методам, но и объектам класса, переменным, любым членам созданного класса. Все объявленные члены класса с ключевым словом public, будут доступны всем другим существующим в программе классам, поэтому стоит призадуматься, а хорошо ли это? Например, у вас есть какие-то данные, которые не должны быть доступны другим классам, что тогда? Для этого в языке Java существует еще пара ключевых слов: private и protected, благодаря которым вы защищаете свои члены классов от общего доступа. По умолчанию, если вы не используете ключевые слова, Java назначает всем членам класса спецификатор public. Метод main (), всегда должен вызываться с ключевым словом public, чтобы для всех классов программы метод main ( ) был доступен. Как только программа начнет работать, первым делом она ищет метод ma in () и постепенно, шаг за шагом, а точнее, строка за строкой, выполняет все предписанные действия в методе main ( ) .
1.4. Конструктор Каждый класс обязан содержать конструктор. Конструктор - это тот же самый метод, но имеющий название класса, например: class Telefon { Telefon(); / / конструктор int w, h, s; // переменные void A r e a ( ) ; // метод } Конструктор позволяет инициализировать создаваемые объекты данного класса с заданными значениями. Каждый класс имеет конструктор, и если вы явно не записали строку кода (как в нашем случае Telefon ( ) ), Java автоматически создаст его за вас, такой конструктор носит название конструктора по умолчанию. Конструкторы в программировании очень полезны и ни одна профессиональная программа не обходится без конструкторов. Чтобы действительно ощутить мощь конструктора, надо создать конструктор с аргументами, благодаря которым можно инициализировать данные класса.
Объекты классов class Telefon { int w, h, s; Tele.fon (int a, int b) { w = a; .
// конструктор
h = b; }
void Area ( ) // площадь телефона . { S = w*h;
При создании объекта (об этом чуть позже), вы можете указать необходимые значения для параметров а и Ь, например: а = 70, b = 100. Эти заданные числа автоматически присвоятся переменным w и h при создании объекта класса Telefon. Тем самым произойдет инициализация объекта с необходимыми значениями. Количество конструкторов в классе ограничивается только вашей фантазией и здравым смыслом. Например, можно создать два конструктора классу Telefon: Telefon (int a, int b) ; Telefon (char a, char b) ; В этом случае при создании объекта по переданным параметрам конструктору класса, компилятор выберет сам необходимый конструктор и создаст заданный объект.
1 .5. Объекты классов Объекты представляют класс, наследуя от своего класса все возможности. Объявить объект очень просто, необходимо вначале указать класс, а потом объект этого класса. Например: Telefon object; Точно так же как создается переменная int а, создается и объект класса. Такая запись создаст пустой объект класса, инициализирующийся значением null. Конечно, это еще не полноценный объект, а всего лишь ссылка на данный класс. Чтобы создать полноценный класс, нужно воспользоваться ключевым словом new, с помощью которого происходит выделение области памяти для содержания создаваемого объекта. Telefon object; object = new TelefonO;
Основы языка Java или
Telefon object = new T e l e f o n ( ) ; Обе записи создания объекта класса Telefon одинаковы. Чаще всего используется вторая запись, но это можно оставить на усмотрение программиста. Сначала создается пустая ссылка object, а потом с помощью ключевого слова new выделяется память для объекта и он инициализируется конструктором класса Telefon ( ) . Именно тут и необходим хорошо продуманный конструктор с параметрами, инициализирующий объект с заданными значениями. Теперь давайте рассмотрим пример посложнее. Создадим класс с конструктором для инициализации высоты и ширины дисплея и в методе main ( ) создадим объект класса Telefon, вычислив при этом площадь экрана абстрактного телефона. class Telefon { int w, h, s; // конструктор класса Telefon Telefon (int a, int b) { w = a; h = b; -}
// метод, вычисляющий площадь экрана void Area ( ) { S = w*h; // class RunTelefon может находится в файле. RunTe 1 е f on . j ava class RunTelefon { public static void main (String a r g s [ ] ) { // создаем объект класса Telefon Telefon object = new Telefon (70, 90); // вычисляем площадь дисплея object .Area ( ) ;
Разберем весь пример более подробно. Итак, мы создаем класс Telefon с тремя переменными: w, h и s, в которых впоследствии будут храниться, соответственно, ширина, высота и площадь дисплея телефона. Далее создаем конструк-
Объекты классов тор класса Telefon для инициализации высоты и ширины дисплея. Метод Area ( ) класса Telefon вычисляет площадь экрана, сохраняя полученный результат в переменной s. После этого идет класс RunTelef on с методом main ( ) , являющийся входной точкой для всей программы. Как только написанное приложение начнет работать, программа найдет метод main ( ) и начнет выполнять содержимое программы. В первой строке кода метода main( ) происходит создание объекта класса Telefon со значениями ширины — 70 и высоты - 90 для экрана телефона. Вторая строка кода вызывает метод Area ( ) , вычисляющий площадь дисплея. Метод Area ( ) нельзя просто так вызвать в программе, он должен ссылаться на объект класса Telefon. Запись object .Area ( ) как раз и указывает на то, что объект класса Telefon вызывает метод Area ( ) . Если имеется несколько объектов класса Telefon, то есть несколько различных телефонов, тогда вызов метода Area ( ) должен происходить для каждого из объектов класса Telefon, например: objectl .Area ( ) ; object2 .Area ( ) ; objects .Area ( ) ; Для каждого из объектов класса Telefon будет вычисляться только своя площадь экрана. Давайте рассмотрим еще более сложную программу, создав несколько объектов класса Telefon, а заодно используем другую схему работы метода Area ( ) , воспользовавшись ключевым словом return. class Telefon { int w, h, s, n,/ / конструктор Telefon (int a, int b) {
w = a; h = b; } / / вычисляет площадь дисплея int Area ( ) { return w*h;
// class RunTelef on может находится в файле RunTelef on . j ava class RunTelefon { public static void main (String [] args)
'
Основы языка Java // создадим объект Siemens Telefon Siemens = new Telefon (101, 8 0 ) ; 1 1 создадим объект nokia Telefon nokia = new Telefon (128, 128); // сохраним полученную площадь в s s = Siemens .Area ( ) ; // сохраним полученную площадь в п n = nokia. Area ( ) ;
В реализации класса Telefon изменился только метод Area ( ) , использовалось ключевое слово return. С его помощью результат умножения высоты на ширину, то есть результат работы всего метода возвращается для дальнейшего использования в коде программы. А в рабочем цикле программы в методе main ( ) , этот результат сохраняется в двух переменных s и N для каждого из объектов класса Telefon. В данном случае площадь экрана для объекта Siemens равна 101x80=8080, а для объекта nokia 128x128=16384 и оба результата хранятся в различных переменных. У вас наверно сразу возникает вопрос, а как увидеть получившийся результат? Действительно, просчитать значение не составляет труда, но хотелось бы увидеть полученный результат на дисплее. Для этого в Java существует встроенный метод print In ( ) . Чтобы увидеть на экране результат работы метода Area ( ) , нужно добавить вызов метода print In ( ) . s = Siemens .Area (); System. out .print In ("Площадь экрана Siemens" + s) ; n = nokia. Area () System. out .println ( "Площадь экрана nokia" + n) ,Метод print ( ) , как уже говорилось, встроенный и принадлежит классу System, поэтому такая запись, out - это поток ввода, связывающий программу с консолью. Реально в программировании телефонов метод println ( ) используется, как правило, в диагностических целях, но как логическое завершение примера подойдет. С помощью кавычек ограничивается количество выводимого на экран текста, это необходимое условие. Запись, + s, применяет операцию конкатенации на основе оператора +, с помощью которого на экран выводится значение переменной s, то есть целочисленное значение равное площади экрана. Резюмируя объектно-ориентированное программирование, можно с уверенностью заявить - это не сложно, не страшно, достаточно понятно и, что самое главное, просто в использовании. Создав необходимый класс, объявив объект и воспользовавшись методами созданного класса, вы получаете неограниченные возможности в программировании приложений. Но главное - большое количество необходимых классов и методов уже созданы за вас и собраны в специальные библиотеки, о которых мы поговорим в конце этой главы. Вам же остается только воспользоваться этими готовыми классами, создавая свои объекты этих классов.
Условные операторы
1.6. Условные операторы Когда мы создавали и использовали класс, RunTelef on, с методом main ( ) , я говорил, что программа выполняет прописанный код строка за строкой и это действительно так. В небольших программах, таких, как мы создали, этого вполне достаточно, но в действительно огромных программах такой подход не логичен. Нельзя «прыгать» по программе, надо идти от строки к строке. Но если все же требуется перейти в программе к какому-то методу или месту программы, что тогда? Для этого в языке Java существуют условные операторы. Рассмотрим ситуацию, которая более наглядно объяснит смысл операторов. Допустим, вы дома, у вас нет хлеба и надо сбегать в булочную за углом. Прежде чем идти в булочную вы обязательно проверите, есть ли у вас деньги на покупку хлеба и только потом отправитесь в магазин за хлебом. Здесь имеет место предусловие наличия денег, выполнение которого приводит вас либо к походу за хлебом, либо к соседу за деньгами. В том случае, если не рассматривать это предусловие, то вы бы вышли и пошли в магазин, а уже придя, стали бы искать по карманам. Вот для этого и существуют условные операторы. В языке Java имеется несколько условных операторов. Первый из них: if /else - представляющий собой такую сдвоенную конструкцию. Синтаксический шаблон условного оператора if /else выглядит следующим образом: if (условие) { // действие №1 '}'
else { // действие №2 } Переводя эту конструкцию на русский язык, можно сказать: если ( i f ) некое условие верно, то перейти к действию №1, а иначе (else) выполнить действие №2. Такая сдвоенная конструкция if /else может быть не обязательна, иногда достаточно лишь записи оператора if. Можно использовать вложенные операторы if /else, например:
if (условие 1 ) {. '' if (условие 2 )
Здесь проверяется первое условие и если оно верное, то происходит переход к следующему оператору if, если и это условие верное, то выполняются дей-
Основы языка Java ствия и во втором и в первом условном операторе. Если же условие во втором операторе if не верно, то выполняются действия только первого оператора if. Условные операторы в программировании на Java используются постоянно и важно понимать их общий принцип работы.
1 .7. Управляющий оператор В языке Java существует управляющий оператор switch, который можно в принципе отнести к условным операторам. Он тоже основан на неких условиях, но предоставляет многовариантное ветвление для выбора пути заданных действий. Посмотрите на синтаксический шаблон этого оператора: switch (условие) { case 1 : // действие 1 break; case 2 : // действие 2 break; case 20: // действие 20 break; default: // действие по умолчанию break; Вся конструкция оператора switch основана на метках case, имеющих целочисленные значения. Когда условие, проверяющееся оператором switch совпадает с одним из значений метки case, то последующие за меткой действия будут выполнены. Если ни одно из условий не совпало с меткой case, то будут выполнены действия, следующие за меткой default. Оператор break, использующийся в конце всех действий для каждой метки очень важен. Когда условие совпадет с одной из меток и начнется выполнение указанных действий для этой метки, то выходной точкой служит оператор break. Если вы случайно забудете поставить оператор break, то ваша программа начнет выполнять следующую метку, сведя тем самым ваши усилия по выбору заданных действий на ноль. Никогда не забывайте ставить оператор break для каждой из меток!
1 .8. Циклы Вы задумывались когда-нибудь над тем, зачем вообще существуют программы? Если упростить и обобщить ответ на этот вопрос, то выяснится, что программы необходимы для автоматизации рабочего процесса, увеличения скорости вы-
Циклы полняемой работы, избавления человека от тысяч монотонных действий и так далее. Сейчас мы как раз и остановимся на повторяющихся друг за другом Действиях. Цикл - это последовательное выполнение повторяющихся действий на основе заданного предусловия. Например, нужно переставить сто ящиков из одного угла в другой. Если это каким-то образом записать на языке Java (к сожалению, переставить за вас ящики Java не сможет), то получится запись в сто строк наподобие этой: 1) взять ящик №1 и поставить другой угол; 2 ) взять ящик №2 и поставить другой угол; 3) взять ящик №3 и поставить другой угол; 100) взять ящик №100 и поставить другой угол;
Сто строк кода - это уже много, но бывает и тысяча. Для этих целей, а именно - упрощения записи повторяющихся действий и служат циклы. Существует три оператора представляющих циклы в языке Java- это while, do/white и f dr. Каждый из операторов необходим в своей ситуации, но все же чаще всего используется оператор for. Рассмотрим по порядку каждый из операторов.
1.8.1. Оператор while Синтаксическая запись оператора while выглядит следующим образом: while (условие) { // действия , } Также имеет место выполнение определенного предусловия, но в отличие от оператора i f /el se, данная конструкция построена на циклах проверки условия. Когда программа доходит до оператора while, если предложенное условие истинно, происходит выполнение всех действий в блоке из фигурных скобок {...}. После выполнения этих действий, снова происходит очередная проверка условий после оператора while и если условие опять истинно, происходит повторное выполнение действий в блоке. Действия в блоке выполняются до тех пор, пока условие не станет ложным, тогда происходит выход из цикла while. В основном все циклы упрарляются при. помощи так называемых счетчиков. Рассмотрим не большой пример:
int i. = 0; while (i < 1Q) { // действия
.
Основы языка Java Сначала переменной i присваивается значение 0, далее происходит проверка условия i< 10, если переменная i меньше цифры 10, выполняются все действия в блоке цикла. В конце блока переменная i увеличивается на 1 и вновь проверяется условие в цикле. И так ровно десять раз для нашего примера. Переменная i служит счетчиком для цикла while. Отсутствие операции по увеличению переменной i на единицу приведет к бесконечному циклу, поскольку 0 всегда будет меньше десяти. В циклах так же можно использовать оператор декремента, например: int i = 10;
while ( i > 0 ) { / / действия i— A } Те же действия, но уже в обратную сторону. Но все-таки чаще всего используется оператор декремента. В цикле while имеется возможность использования булевых переменных, содержащих значения f a l s e или true. После оператора while происходит проверка предусловия, то можно воспользоваться булевой переменной, например: boolean i = true; while ( i ) { // действия }
Переменная i истинна, ей присвоено значение true, поэтому происходит выполнение цикла whi 1 е. Единственное о чем необходимо позаботиться - это о выходе из такого цикла, поскольку переменная i истинна, то цикл while будет выполняться бесконечно и такие циклы носят названия бесконечных циклов. Напоследок хочу еще обратить ваше внимание на оператор равно ==. Если записать цикл таким образом:
int i = О while (i == 5) {. / / действия
То получится вполне работоспособный цикл, а вот если вы ошибетесь или по привычке воспользуетесь классическим вариантом оператора равно =, использующимся в математике, то у вас будет проблема в виде бесконечного цикла. int i = О
while (i =' 5)
Циклы / / действия
В предусловии происходит присвоение переменной i значения 5, а оттого, что это действие не запрещено, то произойдет выполнение блока. цикла. В конце которого значение i увеличится на один, но в предусловии после оператора while, переменной i новь будет присвоено значение пять — это пример простого бесконечного цикла и как следствие, классическая ошибка, случающаяся с начинающими программистами.
1 .8.2. Цикл do/while Только что рассмотренный нами цикл while при определенных условиях может и не заработать. Например, если условие будет изначально ложно, то цикл не выполнится ни разу. Программа, дойдя до строки кода с оператором while, проверит условие и если оно будет равно false, проигнорирует весь цикл и перейдет к коду, следующему сразу за циклом while. Но иногда возникает необходимость в выполнении цикла по крайней мере один раз. Для этих целей в Javaсуществует цикл do/while. Запись и создания цикла do/while осуществляется следующим образом:
do • • { • //' действия }while (условие) Между операторами do и while существует тело цикла, которое будет выполняться до тех пор, пока постусловие, следующее за оператором while, не будет ложно. Тело цикла выполнится, по меньшей мере, один раз, после чего будет произведена проверка условия. Цикл do /while используется не часто, но порой оказывается незаменим. \
.
1.8.3. Цикл for Это самый распространенный цикл, используемый в программировании, основанный на управлении счетчиком. Смысл работы цикла for схож с рассмотренными выше циклами while и do/while. Посмотрите, как выглядит цикл for: for (int i = 0; i < 10; i++) { / / действие . • \
После ключевого слова for, следует условие выполнения цикла. Само же условие объединяет в себе три этапа по инициализации счетчика: i = 0, провер-
Основы языка Java ка условия i < 10 и увеличение переменной i на единицу. Когда программа доходит до цикла for, то происходит инициализация счетчика i = 0 и проверяется условие i < 10. Далее программа переходит в тело цикла. По окончанию всех действий в цикле for, происходит обращение к третьему этапу цикла: i++, увеличивая счетчик на единицу. После чего сразу же происходит переход ко второму этапу - проверке переменной i < 10 и повторный выход в тело цикла. Весь цикл продолжается до тех пор, пока условие i < 10 не станет ложным. Цикл for используется постоянно при инициализации массива данных, где без него очень сложно, а порой и не возможно обойтись. Так же как и в цикле while возможно использование оператора декремента, например: f o r - ( i n t i = 10; г > 0; i-). {
//действие } Используя любую выбранную конструкцию цикла, вы получаете очень мощный( инструмент программирования, избавляющий вас от написания большого количества строк кода.
1.9. Массивы Очень часто в программировании встречается большое количество однотипных данных. Для того чтобы не объявлять, скажем, сто переменных, существуют массивы данных. Массив - это набор однотипных значений. В языке Java для создания массивов предусмотрена специальная запись: int[]M;
С помощью такой записи создается пустая переменная, содержащая определенный массив данных. Объявление массива происходит так же как и объявление объекта класса. Необходимо воспользоваться ключевым словом new чтобы выделить память массиву и явно инициализировать его с количеством элементов. Например: i n t [ ] M = new i n t [ 2 0 ] ; В этой строке кода был создан целочисленный массив из двадцати элементов. К каждому из элементов массива можно обратиться при помощи индекса М [п], для сохранения либо изъятия значения заданного элемента. М [ 0 ] = 3; М [ 1 ] = 5; М [ 2 ] = 20;
Индекс любого созданного массива всегда начинается с 0, об этом нужно помнить. Чтобы инициализировать массив данных, например из пятидесяти эле-
Массивы ментов, должно потребоваться пятьдесят строк кода, но в нашем распоряжении имеется цикл for, прекрасно справляющийся с этой задачей. i n t [ ] M = new int [ 5 0 ] ; for (int i = 0; i<5'0; i + +)
{
M[i]
= i;
} В этом примере происходит инициализация каждого элемента массива от О до 49, соответственно, такими же значениями. Можно инициализировать массив другим способом, без ключевого слова new. i n t [ ] M = { О , 1, 2 , 3, 4} В этом случае каждый элемент массива инициализируется пятью числами от О до 4. Все вышеперечисленные примеры создавали простой одномерный массив данных, но иногда приходится представлять данные в виде парных значений. Например, координаты по X и по Y в системе координат. Для этого в Java существуют многомерные массивы данных. int stroka = 10; int stolbec = 10; i n t [ } [ ] M = -new [stroka] [stolbec]; Многомерные массивы представлены в виде таблицы. Чтобы получить доступ к заданному элементу массива, нужно указать в какой строке и в каком столбце находится элемент массива. Точно так же в высшей математике происходит работа с матрицами. Многомерный массив данных можно инициализировать с помощью фигурных скобок:
{55 3, 8}, {7, 12, 16), {9, 12, 14} } Инициализация массива данных при помощи цикла for немного сложнее, но очень эффективная и используется постоянно. Например, у вас есть большой массив данных, который требуется обнулить. Вот как будет выглядеть запись для этого массива данных:
i n t [ ] [ ] М = new int [100] [50] ; for (int i = 0; i < 100,- i + +) for (int a = 0,- a < 50; a++) M [ i ] [a] = 0; Многомерные массивы позволяют хранить большое количество данных при минимуме записанного кода, сохраняя при этом его понятность и читабельность.
Основы языка Java
1.10. Наследование В языке Java имеется термин наследование. Это очень мощный инструмент, без которого не обходится ни одна профессионально написанная программа. Каждый из вас, читающий эти строки обязательно хочет стать профессиональным программистом, поэтому стоит подробно рассмотреть механизм наследования. Наследование - это механизм, позволяющий наследовать от вышестоящего в ие'рархии класса все его возможности. Что значит класс, стоящий выше в иерархии? В языке Java существует термин суперкласс и подкласс. Например, имеется некий класс Siemens: class Siemens {
int w, h; int Area ( ) { return w*h;
Чтобы создать подкласс класса Siemens, необходимо воспользоваться ключевым словом extends:
class SiemensMSS extends Siemens { // члены класса }
Класс SiemensMSS является подклассом класса Siemens, в свою очередь класс Siemens является Суперклассом для класса SiemensMSS. Класс SiemensMSS наследует все члены своего суперкласса Siemens и имеет возможность доступа к ним при одном условии: все члены суперкласса Siemens, к которым вы впоследствии захотите получить доступ, должны быть объявлены со спецификатором public. Поскольку мы не определяли вообще никакого спецификатора, а это по умолчанию равно ключевому слову public, то подкласс SiemensMSS, будет иметь доступ ко всем членам своего суперкласса Siemens. Вы можете воспользоваться методом Area ( ) и переменными w и h. Вам не нужно переопределять переменные и метод суперкласса Siemens, но вы можете добавлять дополнительные переменные и методы для подкласса SiemensMSS, реализующие свои специфические действия для этого подкласса. Давайте рассмотрим небольшой пример по созданию суперкласса и подкласса. Как вы уже, наверное, догадались, я воспользовался маркой телефона Siemens М55 для названия подкласса. Чтобы не обижать других производителей телефонов, рассмотрим пример для Nokia. // суперкласс Nokia class Nokia
Наследование // высота, ширина и площадь дисплея int dh, dw, ds; // метод, вычисляющий площадь дисплея int Area ( ) { return dw * dh;
// подкласс Nokia3100 class Nokia310 extends Nokia' { 7/ высота, ширина и площадь всего телефона int th, dw, .ds; У/ метод, вычислякшщий площадь телефона int tArea ( ) { .return tw * th;
// входная точка приложения class RunNokia
;| public static. void main (String argsf]) { // при создании объекта используется конструктор по умол чанию Nokia3100 nokiaSlOO = new Nokia3100(); // задаем значения для переменных nokiaSlOO.dh = 128; nokia.3100.dw .= 128; nokia3100.th = 102; nokia3100.tw = 43; // вычисляем площадь дисплея ds = nokia.dArea ( ) ; // вычисляем полощадь телефона dt = nokia. tArea ( ) ;
Создав подкласс Nokia3100, вы получите доступ ко всем членам суперкласса Nokia, определенные как public. Используя оператор «.» (точка), вы открываете доступ к переменным и методам суперкласса. При создании объекта суперкласса, например Nokia nokiasuper = new Nokia ( ) , объект созданного
Основы языка Java класса может пользоваться своими членами класса, но уже члены подкласса ему не доступны. Инач& говоря, подкласс расширяет свой суперкласс, добавляя новые члены в подкласс, тем самым, подстраивая под себя новые, необходимые только подклассу, члены класса, оставляя за собой возможность использования членов суперкласса. Суперкласс вправе иметь сколько угодно подклассов, например, в рассмотренном примере можно создать еще десяток-другой подклассов: NokiaSlOO, NokiaGGOO, Nokia2100 и так далее. Но каждый из подклассов может иметь только один суперкласс. Множественные наследования в языке Java не предусмотрены. Но каждый из подклассов может иметь свой подкласс, и такая цепочка наследования может длиться до разумной бесконечности.
1.10.1. Конструктор суперкласса В рассмотренном. примере по созданию суперкласса и подкласса Nokia, умышленно использовался конструктор по умолчанию. Ситуация с конструкторами суперклассов требует отдельного внимания. Когда в программе происходит вызов конструктора, то вызов осуществляется согласно всей иерархии наследования. Первым вызывается конструктор самого первого суперкласса и опускается ниже по все иерархии наследования. Но иногда необходимо обратиться к ближайшему конструктору суперкласса и тогда используется ключевое слово super. Рассмотрим небольшой пример. // суперкласс Nokia class Nokia { // конструктор суперкласса Nokia // тело класса Nokia } // подкласс NokiaSeries60 class NokiaSeriesGO extends Nokia { // конструктор подкласса NokiaSer.iesGO NokiaSeriesGO(int a, int b) ; // тело подкласса NokiaSeriesGO } // подкласс NokiaGGOO для суперкласса NokiaeSeriesGO class Nokia6600 extends NokiaSeries60 { 7/ конструктор подкласса NokiaGSOO NokiaGGOO (short f, short' b, short c) { super (a, b) // тело конструктора.
Наследование // подкласс NokiaSlOO для суперкласса NokiaeSeries60 class Nokia6100 extends NokiaeSeries60 { // конструктор подкласса Nokia6100 Nokia6100 (char a, char b) { super (a, b) // тело конструктора } // тело подкласса Nokia6100 } Если вы желаете воспользоваться конструктором ближайшего суперкласса, в конструкторе подкласса первым должно идти ключевое слово super с параметрами для необходимого конструктора суперкласса. Ключевое слово super имеет двойную смысловую нагрузку и может использоваться не только для вызова конструктора суперкласса. Второй вариант использования ключевого слова super, заключается в доступе к невидимому члену суперкласса. Сейчас мы коснулись так называемого вопроса видимости. Вы не задумывались над тем, что будет, если методы или переменные в суперклассе и подклассе будут совпадать по именам? Дело в том, что если подкласс будет иметь одинаковые названия любых членов класса, то он будет использовать только свои члены класса. Все данные суперкласса окажутся недоступными или невидимыми в силу совпадения названий. Для этих целей может быть использовано слово super. Посмотрите на пример иллюстрирующий способ его использования: // суперкласс Siemens class Siemens { int a, b; } // подкласс SiemensMC62 class SiemensMC62 extends Siemens { int .a, b; // конструктор подкласса SiemensMC62 SiemensMC62 (int c, int d)
£ stfper.a super. b a = с; b = .d;
= с,- // = d; // // для а // для b
для а в суперклассе для b в суперклассе подкласса подкласса
-' • •
,
Основы языка Java Использование ключевого слова super очень похоже на обращение объекта класса к методам и переменным. Когда необходимо получить доступ к членам суперкласса, имеющим одинаковые названия, воспользуйтесь ключевым словом super или поступайте проще - давайте различные имена для членов суперкласса и подкласса. В языке Java существует еще одно ключевое слово this, выполняющее похожие действия. При помощи этого ключевого слова можно произвести вызов любого другого конструктора того же класса либо использовать для указания ссылки на параметр, отсутствующий в конструкторе класса. Подводя итог темы наследования необходимо упомянуть о классе Object. В языке Java все классы наследуются от большого суперкласса Obj ect. Это происходит автоматически и беспокоится о явном наследовании при помощи ключевого слова extends не нужно.
1.11. Интерфейсы В программировании мобильных телефонов на Java 2 ME очень часто используются интерфейсы. Интерфейс задает классу, что именно должен делать этот класс, но, не говоря каким образом должны быть реализованы эти действия, то есть, это некая спецификация, в рамках которой происходит реализация необходимых действий. Создание интерфейса совершается при помощи ключевого слова interface, а для реализации каким-либо классом возможностей интерфейса используется ключевое слово implements. Чтобы более четко разобраться в работе с интерфейсами рассмотрим небольшой пример: public interface Mylnterface { int Inkriment { ) ; } •class MyOne implements Mylnterface { int a ; // реализация метода Inkriment () для класса MyOne public int Inkriment () { . . a = 9++; return a;
class MyTwo implements Mylnterface { int a; // реализация метода Inkriment () для класса MyTwo public int Inkriment ()
Пакеты a = 2 + +;
return a;
Созданный интерфейс Mylnterf асе имеет один пустой метод Incriment ( ) . Тело метода отсутствует, есть только его декларация, а класс МуОпе реализует данный интерфейс для своих нужд. В свою очередь класс MyTwo тоже реализует метод Incriment ( ) в необходимой ему форме. Интерфейс задает, что именно надо сделать, а класс, реализующий данный интерфейс, решает, как ему это сделать. Все методы, заключенные в интерфейсе, обязательно должны быть созданы в классе, реализующим этот интерфейс. Интерфейсы не являются классами, поэтому создать интерфейс при помощи ключевого слова new невозможно, но создавать переменные интерфейса можно, в случае если они сохраняются на объекты класса. Любой интерфейс может наследовать другой интерфейс при помощи ключевого слова extends, Интерфейсы очень ярко отражает полифонизм языка Java.
1.12. Пакеты При наличии большого количества своих классов, можно создавать пакеты, для этих классов, коллекционируя их. С помощью ключевого слова package можно создать пакет для класса. Для этого в самом начале файла, где вы пишете исходный код для класса, сделайте запись, например следующую, для созданного ранее в разделе 1.10.1 класса Nokia: package Nokia; В последствии вы сможете получить доступ к пакету с этим классом с помощью спецификатора import в начале файла, где вам необходим класс Nokia. import Nokia . * Оператор звездочка в конце импорта класса Nokia обозначает доступ ко всем классам этого пакета. Но возможно обращение и к отдельному классу всего пакета, например: import Nokia. NokiaeSeries60 .Nokia6600; При условии, конечно, что все эти классы существуют в пакете Nokia. Если вы собираетесь использовать много классов из пакета, то лучше воспользоваться оператором звездочка, чем перечислять каждый класс в отдельной строке кода. Кроме этого пакеты имеют еще одну денную возможность - при создании своих классов существует вероятность того, что какой-нибудь программист, собирающий яблоки в Новой Зеландии возьмет и назовет свой созданный класс точно таким же именем. В этом случае возникает конфликт имен вызывающий исключительную ситуацию. Но если пользоваться возможностью создания пакетов, такая вероятность повторения снижается. Даже если названия созданных классов будут одинаковыми, содержаться они будут в разных пакетах. Конфликта не возникнет. Слышу провокационный вопрос: а если названия пакетов совпадут? Да вы правы,
Основы языка Java есть же сказка про Буратино от двух разных авторов... В таком случае можно воспользоваться рекомендуемой компанией Sun Microsystems, создавшей язык Java, схемой записи по зарезервированному домену в Интернете, например: package ru.dmk; Или как в случае упомянутой сказки о деревянном человечке:
„
package Buratino; •package Pinocchio; И избежать тем самым конфликта имен. Такой способ записи по домену действительно работает и на этой схеме построены все пакеты в Java. Язык Java имеет огромное количество предопределенных классов, существующих в виде библиотек. Все библиотеки разбиты на пакеты по своему назначению. Платформа Java 2 ME состоит из одиннадцати пакетов: Q java.io; Q java.lang; G java.util; G javax.microedition.lcdui; Q javax.microedition.lcdui.game; Q javax.microedition.io; Q javax.microedition.media; Q javax.microedition.media.control; О javax.microedition.pki; G javax.microedition.midlet; Q javax.microedition.rms. Каждый из пакетов содержит множество классов с различной областью применения. Имеются математические классы, классы, отвечающие за работу с сетью, классы ввода-вывода, классы утилит и так далее. Более подробно каждый из пакетов будет рассмотрен в главе 2. Для того чтобы воспользоваться имеющимися классами и методами, необходимо в начале исходного кода импортировать нужный для работы пакет: import j a v a . l a n g . * Затем можно воспользоваться, к примеру методом abs (int a ) , класса Math, возвращающим целочисленное значение переменой.
int a = 9; int х = Math.abs(а); Импортируя пакеты в программу, вы упрощаете разработку приложения, поскольку имеется огромное количество готовых классов и достаточно просто создать объект импортированного класса и пользоваться всеми его методами и возможностями. В этом приложении мы рассмотрели язык программирования Java вкратце, но изученного материала будет достаточно для прочтения этой книги и освоения азов программирования мобильных телефонов на Java 2 Micro Edition.
Приложение 2. Справочник по Java 2 Micro Edition В этом приложении содержится исчерпывающий справочный материал по всем пакетам, интерфейсам, классам, конструкторам классов и константам платформы Java 2 Micro Edition. Справочник выполнен на основе имеющейся документации к платформе Java 2 ME, находящейся на сайте компании Sun Microsystems, по адресу в Интернет: http://java.sun.com. Аналогичная документация также поставляется с платформой Java 2 ME, которую вы найдете на компакт-диске, приложенном к книге, в составе среды программирования SUN ONE Studio 4 Mobile Edition и J2ME Wireless Toolkit 2.1. Справочник рассматривает все пакеты, имеющиеся в составе платформы Java 2 ME. Каждый пакет содержит множество интерфейсов, классов, конструкторов и констант. Для всех имеющихся компонентов каждого пакета дается краткая характеристика, на основании которой вам будет очень легко сориентироваться в создании приложений для платформы Java 2 Micro Edition.
2.1. Пакет Java.lang Содержит системные классы или основы языка Java.
2.1.1. Интерфейс Runnable Q Использование интерфейса Runnable обеспечивает создание, потока в программах. Метод Q void run ( ) - запускает поток в приложении.
2.1.2. Класс Boolean Объектно-ориентированный класс-оболочка или как еще говорят «обвертка» для типа Boolean. Конструктор О Boolean (boolean value) - создает объект класса Boolean. Методы Q boolean booleanValue () - возвращает значение объекта класса Boolean; Q boolean equals (Object obj ) - возвращает значение true, если это объект класса Boolean;
Щ
Справочник по Java 2 Micro Edition
О int hashCod'e ( ) - возвращает специальный код (хеш-код) объекта класса Boolean; Q String toString ( ) - возвращает объект класса String для булевой переменной.
2.1.3. Класс Byte Объектно-ориентированный класс оболочка, для простого типа Byte. Конструктор Q Byte (byte value) - создает объект класса Byte. Методы CJ byte byte Value ( ) - возвращает значение объекта класса Byte; О boolean equals (Object obj ) - возвращает значение в байтах для объекта класса Byte; Q int hashCode ( ) - возвращает специальный код (хеш-код) объекта класса Byte; 'Q s t a t i c byte parseByte (String s ) - возвращает значение в байтах для указанного объекта String; О static byte parseByte (String s, int radix) - возвращает значение в байтах для указанного объекта String на основе системы исчисления; О String toString ( ) - возвращает объект класса String, представленный значением Byte. Константы О s t a t i c byte MAX_VALUE - максимальное значение в байтах; Q static byte MIN_VALUE - минимальное значение в байтах.
2.1.4. Класс Character
\
Объектно-ориентированный класс-оболочка для простого типа Char. Конструктор О Character (char value) - создает объект класса Character. Методы Q char charValue () - возвращает значение объекта класса Character; Q s t a t i c int digit (char, ch, int radix) - возвращает числовое значение на основе системы исчисления; Q boolean equals (Object o b j ) - сравнивает объект; Q int hashCode () - возвращает специальный код (хеш-код) объекта класса Character; Q static boolean isDigit(char ch)-узнает, является ли значение ch числовым значением; Q static boolean isLowerCase (char ch) - определяет, является ли символьное значение строчным;О static boolean isUpperCase (char ch) - определяет, является ли символьное значение заглавным;
Структура компакт-диска • cdsetupl.0.0.76 - программа для соединения телефона с компьютером; Q Sony Ericsson - в папке представлено программное обеспечение компании Sony Ericsson: • • semcJ2me_sdk_2_l_0_beta - Sony Ericsson J2ME SDK 2.1; • semc_SDK21_patch - патч к Sony Ericsson J2ME SDK 2.1; • Packagel_1.5.9.2 - программа для соединения телефона с компьютером; Q Motorola - в папке представлено программное обеспечение компании Motorola: • sdk41ga - Motorola Lanchpad for J2ME; ' G Samsung - в папке представлено программное обеспечение компании Samsung: • JSDKvlJ) - SamsungJSDK 1.0.
Приложение 3. Структура компакт-диска Компакт-диск включает в себя следующие папки: О SDK - содержит средства программирования: • ffj_me_win32 - среда программирования Sun One 4 Mobile Edition; • j2me_wireless_toolkit-2_l-windows — среда программирования J2ME Wireless Toolkit 2.1; • J2re-l_4_l_02-windows-i586 -Java Runtime; • j2sdk-l_4_2_03-windows--i586-p -Java SDK SE;' Q Code - содержит все исходные коды из книги; Q' Nokia - в папке представлено программное обеспечение компании Nokia: • Linux — папка с инструментариями под операционную систему Linux; • nds_jme_linux_v2_0.tar - Nokia Developer's Suite 2.0 for Linux; • nS30_jme_concept_sdk_linux_bO_2.tar — эмулятор тридцатой серии; • nds_jme_v_2_J) - Nokia Developer's Suite 2.0 for J2ME; • Nokia_S40_DP20_SDK_bet_0[l].5.0 - эмулятор сороковой серии; • nS40_jme_concept_sdk_bO_3 - эмулятор сороковой серии; • nS60_jme_sdk_v2_l - эмулятор шестидесятой серии; • nS90_jme_sdk_vl_0_b - эмулятор девяностой серии; • Nokia_5100_SDK_Final_l_0 - эмулятор телефона 5100; • n3410_sdk_vl_0 — эмулятор телефона 3410; • Nokia_PC_Suite_51_ru - программа для соединения телефона с компьютером; Q Siemens - в папке представлено программное обеспечение компании Siemens: • smtk_0_13_2_59 - Siemens Mobility Toolkit for Java Development; • 2128_0_12_15_1 - эмулятор телефона 2128; • c55_0_12_15_l - эмулятор телефона с55; • сбОа_0_12_24 - эмулятор телефона сбО; • m50_Chinese_setup - эмулятор телефона м50 китайская версия; • m50_setup - эмулятор телефона м50; • т55_0_12_09_1 - эмулятор телефона м55; • т55с_0_12_09_1 — эмулятор телефона м55с; • mc60_setup - эмулятор телефона мсбО; • s55_0_12_l 1_1 - эмулятор телефона s55; • s57_0_12_09_l - эмулятор телефона s57; • sl45_Chinese_setup - эмулятор телефона sl45 китайская версия; • sl45_setup - эмулятор телефона s!45; • s!55_0_12_05 - эмулятор телефона s!55;
Справочник по Java 2 Micro Edition
2.11.5. Класс RecordStore Производит запись данных. Методы Q int addRecord(byte[] data, int o f f s e t , int numBytes) добавляет новую запись в память мобильного устройства; G void addRecordListener(RecordListener listener) —добавляет обработчик событий; Q void closeRecordStore ( ) — закрывает запись; О void deleteRecord(int recordld) - удаляет запись по идентификатору; Q static void deleteRecordStore(String recordStoreName) удаляет запись по имени; Q long getLastModified() - возвращает последнее время изменения записи; Q String getNameO - получает имя записи; Q int getNextRecordlDQ - получает идентификатор последующей записи; Q int getNumRecords ( ) - получает количество доступных записей; Q byte[] getRecord(int recordld) - возвращает копию записи; О int getRecord(int, recordld, byte[] b u f f e r , int o f f s e t ) возвращает данные записи; Q int getRecordSize(int recordld) - получает размер заданной записи; Q int get Size () - получает размер всех записей; Q int getSizeAvailable() - получает количество доступной памяти для записи; Q int getVersionO - получает версию записи; Q static String [] listRecprdStores()'- возвращает список записей; G static RecordStore openRecordStore(String recordStoreName, boolean createlfNecessary) - открывает память для записи; Q static RecordStore openRecordStore(String recordStoreName, boolean createlfNecessary, int authmode, boolean writable) - открывает память для записи; Q.static RecordStore openRecordStore(String recordStoreName, String vendorName, String suiteName) — открывает память для записи; Q void removeRecordListener(RecordListener listener) - удаляет обработчик событий; Q void setMode(int authmode, boolean writable) - изменят режим доступа; Q void setRecordfint recordld, byte[] newData, int o f f s e t , int numBytes) — вводит данные в запись. Константы Q static int AUTHMODE_ANY - позволяет осуществить доступ для любого комплекта мидлетов; Q static int AUTHMODE_PRI VATE - позволяет осуществить доступ только из данной программы.
Пакет javax.microedition.rms Q static int FOLLOWS - первая запись больше второй записи; О static int PRECEDES - вторая запись больше чем первая.
2.11.2. Интерфейс RecordEnumeration Реализует двунаправленный список записи. Методы Q void destroy () - освобождает захваченные ресурсы; Q boolean hasNextElement () - возвращает значение true, если имеются последующие записи; Q boolean hasPreviousElement ( ) - возвращает значение true, если имеются предшествующие записи; О boolean isKeptUpdated ( ) - возвращает значение true в том случае, если сохраняются изменения в записи; Q void keepupdated(boolean keepUpdated) - устанавливает, возможно ли сохранение индексов записей при изменении, удалении или добавлении записей; Q byte [ ] nextRecord ( ) - возвращает копию следующей записи в списке; Q int nextRecordld ( ) - возвращает идентификатор следующей записи в списке; G int numRecords ( ) - возвращает число доступных записей; О byte[]< previousRecord() - возвращает копию предыдущей записи в списке; Q int previousRecordld ( ) - возвращает идентификатор предыдущей записи в списке; Q void rebui Id ( ) - делает запрос для обновления списка доступных записей; Q void reset () - сбрасывает индекс записи к первоначальному значению.
2.11.3. Интерфейс Record Filter Определяет совпадения записей. Метод О boolean matches (byte [] candidate) - возвращает значение true, если кандидат соответствует заданному критерию.
2.11.4. Интерфейс RecordListener Производит обработку событий связанных с изменением, добавлением и удалением записей. Методы Q void reqordAdded(RecordStore recordStore, int recordld) вызывается после добавления записи; О void recordChanged(RecordStore recordStore, int recordld) - вызывай после изменения записи; Q void recordDeleted(RecordStore recordStore, int recordld) - вызван после удаления записи.
Справочник по Java 2 Micro Edition Q void resumeRequest ( ) - переход в активное состояние; Q protected abstract void startAppO - входная точка программы; осуществляет старт приложения.
2.9.2. Исключение Q MlDletStateChangeException - исключает неправильную работу с классом MIDlet.
2.10. Пакет javax.microedition.pki Сертифицирует информацию для безопасной связи.
2.10.1. Интерфейс Certificate
V
Общий сертификат связи. Методы О String getlssuerO - получает используемый сертификат; Q long getNotAfter ( ) - получает момент времени после которого сертификат использовать нельзя; О 1одд getNotBef ore ()-получает момент времени, до которого сертификат использовать нельзя; Q String getSerialNumber () -получает серийный номер сертификата; Q String getSigAlgName () - получает имя используемого алгоритма записи данного сертификата; Q String getSubj ect ( ) - получает название субъекта сертификата; G String getType ( ) , - получает тип сертификата; О String getVersion() - получает версию сертификата.
2.10.2. Исключение Q Certif icateExceptio - обобщенный вид ошибок, возникший при использовании данного сертификата.
2.11. Пакет javax.microedition.rms Осуществляет хранение, удаление, добавление записей в системную память устройства.
2.11.1. Интерфейс RecordComparator Осуществляет сортировку записей. Метод
Q int compare (by te[] reel, byte [] rec2) - сортирует записи.
Константы Q static int EQUIVALENT - две записи одинаковы;
Пакет jovax.microedition.midlet Константы Q static byte BLOCK_END - конец блока воспроизведения; . Q static byte BLOCK_START - стартовая позиция в блоке; Q static byte C4 - нота До; Q static byte PLAY_BLOCK - воспроизвести блок; Q static byte REPEAT - повторить воспроизведение блока; Q static byte RESOLUTION - событие; Q static byte SET_VOLUME - установить громкость; Q static byte SILENCE - без звука; Q static byte TEMPO - темп или скорость воспроизведения; Q s t a t i c byte VERSION - версия атрибута воспроизведения.
2.8.2. Интерфейс VolumeControl Регулирует громкость воспроизведения. Методы Q int getLevelt) - возвращает текущий уровень громкости; Q boolean isMuted() •- определяет состояние сигнала; Q int setLeveKint level) -устанавливает уровень громкости. Значение может находиться в приделах от 0 до 100; Q void setMute (boolean mute) - устанавливает состояние сигнала. .
2.9. Пакет javax. microedition. midlet С помощью этого пакета происходит связь между приложением и мобильным информационным профилем устройства (MIDP).
2.9.1. Класс MIDIet Основной класс мидлета должен наследовать класс MIDIet для управления работой приложения. Конструктор Q protected MIDIet () - закрытый Конструктор. Методы Q int checkPermission (String permission) - получить статус; О protected abstract void destroyApp(boolean unconditional) - заканчивает работу программы; Q String getAppProperty (String key) — получает свойства программного обеспечения; Q void notifyDestroyed ( ) — уведомляет программное обеспечение о конце работы; Q void n o t i f y Paused ( ) — уведомляет программное обеспечение о паузе в работе; Q protected abstract void pauseAppO - переходит в состояние паузы; Q boolean platformRequest (String URL) - дескриптор устройства получает URL;
Справочник по Java 2 Micro Edition Константы Q static String CLOSED - уведомляет о закрытии проигрывателя; Q static String DEVICE_AVAI.LABLE - уведомляет о доступности проигрывателя; Р 'static String DEVICE_UNAVAILABLE-уведомляет о недоступности проигрывателя; О static String DURATION_UPDATED - обновляет состояние; Q static String END_OF_MEDIA - уведомляет 0 конце воспроизведения данных проигрывателем; О static String ERROR - уведомляет об ошибке; Q static String STARTED - уведомляет о начале работы проигрывателя; Q static String STOPPED - уведомляет р конце работы проигрывателя; О static String VOLUME_CHANGED - уведомляет о выборе громкости для воспроизведения.
2.7.5. Класс Manager Менеджер системных ресурсов. Методы Q static Player createPlayer(InputStream stream, String type ) - создает проигрыватель для воспроизведения аудио данных из потока; О static Player createPlayer(String locator) - создает проигрыватель для воспроизведения аудио данных из определенного файла; Q static StringUgetSupportedContentTypes(String protocol) - возвращает список доступных контекстных типов для протоколов; О static String[] getSupportedProtocols(String conteht_ty. ре) — возвращает список доступных протоколов для контекстных типов; Q static void playTone(int note, int duration, int volume) — воспроизводит различные тональные звуки. Константа Q static String TONE_DEV IС E_LOCATOR-необходимая для последовательного воспроизведения тонов устройства.
<
2.7.6. Исключения
•..,;•>.- ' • ' • " • ' • •
О MediaException - исключает ошибки в работе методов этого пакета.
2.8. Пакет javax.microedition.media.control Осуществляет контроль над процессами.
2.8.1. Интерфейс ToneControl Производит воспроизведение тональных звуков на устройстве. Метод О void setSequence (byte [] sequence) - устанавливает тональные звуки.
Пакет javax.microedition.media Методы P Control getControl (String controlType) - получает объект, осуществляющий управление; Р Control [ ] getControls ( ) - получает совокупность объектов осуществляющих управление.
2.7.3. Интерфейс Player Реализует контроль над воспроизведением. Методы Р void addPlayerListener(PlayerListener playerListener) осуществляет обработку событий от определенного проигрывателя; Р void close ( ) - закрывает проигрыватель; Р void deallocate ( ) - освобождает ресурс, занятый проигрывателем; Р String getContentType ()-получает тип аудио данных, воспроизводимых проигрывателем; Р long getDuration() - получает размер аудио файла; Р long getMediaTime ( ) - получает время воспроизведения аудио данных; Р int getStateO - определяет состояние проигрывателя; Р void prefetch ( ) - захватывает ресурсы для последующего воспроизведения данных; Р void realize ()-создает проигрыватель без захвата ресурсов; Р void removePlayerListener(PlayerListener playerListener ) - удаляет установленный обработчик событий; О void setLoopCount (int count) - устанавливает цикличное воспроизведение аудио данных; Р long setMediaTime (long now) - устанавливает время воспроизведения; Р void start () - дает команду на воспроизведение; Р void s t o p ( ) — останавливает воспроизведение. Константы Р static int CLOSED - закрывает проигрыватель; Р static int PREFETCHED - захватывает ресурсы для воспроизведения; Р s t a t i c int REALIZED- приобретает информацию для воспроизведения; Р s t a t i c int STARTED — воспроизведение запущенно; Р static long TIME_UNKNOWN - неизвестное время установки; Р static int UNREALIZED - не произошло захвата ресурсов и информации для воспроизведения.
2.7.4. Интерфейс PlayerListener Получает асинхронные события проигрывателя. Методы
Р void playerUpdate(Player player, String event, eventData) - обновляет состояние проигрывателя.
Object
Справочник по Java 2 Micro Edition Q static int TRANS_ROT180 -сдвинут почасовой стрелке на 180°; Q static int TRANS_ROT270 - сдвинут по часовой стрелке на 270°; Q static int TRANS_ROT90 - сдвинут по часовой стрелке на 90°.
2.6.5. Класс Tiled Layer Осуществляет создание фоновых изображений. Конструктор Q TiledLayer(int columns, int rows, Image image, int tileWidth, int tileHeight) - создает фоновое изображение с заданным количеством столбцов, строк, исходным изображением и шириной и высотой одной ячейки рисунка. Методы Q int createAnimatedTile(int staticTilelndex) - создает анимационный фон и возвращает следующий индекс ячейки; О void f i l l C e l l s ( i n t col, int row, int numCols, int numRows , int tilelndex) - заполняет ячейки; Q int getAnimatedTile (int animatedTilelndex) - получает индекс анимационной последовательности; Q int getCell(int col, int row) - получает ячейку; Q int getCellHeight ( ) - получает высоту ячейки в пикселях; Q int getCellWidth () - получает ширину ячейки в пикселях; О int getColumns ( ) - получает количество колонок, на которое разбито изображение фона; Q int getRows ( ) - получает количество строк, на которое разбито изображение фона; G void paint (Graphics g) -рисуетфон; О void setAnimatedTile(int animatedTilelndex, int staticTilelndex) - устанавливает анимационную последовательность; Q void setCell(int col, int row, int tilelndex) - рисует заданную ячейку; Q void setStaticTileSet(Image image, int tileWidth, int t i 1 eHe i ght) - заменяет набор ячеек.
2.7. Пакет javax.microedition.media Пакет добавлен в профиль MIDP 2.0 и 4ает возможность в создании звукового сопровождения в приложении.
2.7.1. Интерфейс Control Осуществляет контроль над процессами.
2.7.2. Интерфейс Controllable Осуществляет контроль над объектами.
,
Пакет javax.microedition.lcdui.game 2.6.4. Класс Sprite Создает спрайт, представляющий изображение или анимационные фреймы. Конструкторы G Sprite (Image image) - создает не анимированный спрайт; Q Sprite(Image image, int frameWidth, int frameHeight) создает спрайт представленный анимационными фреймами; Q Sprite (Sprite s)-создает спрайт из другого спрайта. Методы G boolean collidesWithfSprite s, boolean pixelLevel) -определяет столкновение между спрайтами; Q boolean collidesWith(TiledLayer t, boolean pixelLevel) — определяет столкновение между спрайтом и препятствием нарисованным при помощи класса TiledLayer; Q public void def ineRef erencePixel (int x, int у) — изменяет опорную позицию спрайта, перенося ее в точку с координатами х и у; Q int getFrameO - получает текущий фрейм; Q int getFrameSeguenceLength () - получает количество элементов в анимационных фреймах; Q int getRawFrameCount ( ) - получает количество не использованных фреймов; Q int getRef P i x e l X t ) - получает координату по оси X для спрайта; Q int getRef PixelY ( ) — получает координату по оси Y для спрайта; Q void next Frame ( ) - осуществляет переход на следующий фрейм; Q void paint (Graphics g) - рисует спрайт; Q void prevFrame ( ) - осуществляет переход на предыдущий фрейм; Q void setFrame(int sequencelndex) - устанавливает заданный фрейм; Q void setFrameSequence (int [] sequence) - устанавливает определенную фреймовую последовательность; О void setlmage(Image img, int frameWidth, int frameHeight ) - изменяет изображение спрайта на новое изображение; О void setRefPixelPosition(int x, int у) - устанавливает координаты по осям X и Y для спрайта; Q void setTrans form (int transform)'- производит трансформацию спрайта. Константы Q static int TRANS_MIRROR - отраженный по вертикали; Q s t a t i c int TRANS_MIRROR_ROT180 - отраженный по вертикали со сдвигом на 180° по часовой стрелке; Q static int TRANS_MIRROR_ROT270 - отраженный по вертикали со сдвигом на 270° по часовой стрелке; Q s t a t i c int TRANS_MIRROR_ROT90-отраженный по вертикали со Сдвигом на 90° по часовой стрелке; О static int TRANS_NONE - без трансформации;
\ Справочник по Java 2 Micro Edition Константы О static int G static int G static int Q static int Q static int Q static int Q static, int О static int О static int
DOWN_PRESSED - движение вниз; FIRE_PRE.SSED - реализует стрельбу из оружия; GAME_A_PRESSED - игровая клавиша А; GAME_B_PRESSED -игровая клавиша В; GAME_C_PRESSED - игровая клавиша С; GAME_D_PRESSED - игровая клавиша D; LEFT_PRESSED - движение влево; RIGHT_PRESSED - движение вправо; UP_PRESSED - движение вверх.
2.6.2. Класс Layer Абстрактный класс, отвечающий за уровни представляемые в игре Методы Q int getHeight ( ) - получает высоту экрана; Q int getwidth ( ) - получает ширину экрана; О int g e t x ( ) — получает горизонтальную координату уровня; Q int getY ()-получает вертикальную координату уровня; О boolean i s V i s i b l e ( ) .— получает видимость данного уровня; О void move (int dx, int dy) - перемещает уровень на dx и dy координаты; Q abstract void paint (Graphics g) - рисует уровень; Q void setPosition(int x, int у ) - устанавливает уровень в позицию, обозначенную в координатах х и у; Q void setVisible (boolean visible) - устанавливает видимость данного уровня.
2.6.3. Класс LayerManager Менеджер имеющихся в игре уровней. Конструктор Q LayerManager ( ) - создает менеджер уровней. Методы Q void append (Layer 1) - добавляет уровень в менеджер уровней; О Layer getLayerAt (int index) - получает уровень с заданным индексом; Q int getSizeO - получает общее количество уровней; Q void insert (Layer 1, int index) - подключает новый уровень в заданный индекс; Q void paint (Graphics g, int x, int у ) - представляет текущий менеджер уровней в заданных координатах; Q void remove (Layer 1) - удаляет уровень из менеджера уровней; Q void setViewWindow(int x, int у, int width, int height) устанавливает область на экране для отображения уровня.
Пакет jovax.microedition.lcdui.game Q static int INITIAL_CAPS_WORD - начальный символ каждого .слова будет печататься с заглавной буквы; Q s t a t i c int NON_PREDICTIVE - значение слов, не используемое в словаре, найдено не будет; U static int NUMERIC - для ввода только целочисленных значений; Q static int PASSWORD - для ввода пароля; Q static int PHONENUMBER - для ввода телефонного номера; D static int UNEDITABLE - редактирование не доступно; , Q s t a t i c int URL - для ввода адреса сайта.
2.5.27. Класс Ticker Создает на экране бегущую строку текста. Конструктор Q Ticker (String str) - формирует бегущую строку текста. Методы О String getstringt) - получает строку текста, заданную для объекта класса Ticker; О void setstring (String str) — устанавливает строку текста для отображения ее на экране с помощью объекта класса Ticker, заменяя ее новой строкой.
2.6. Пакет javax.microedition.lcdui.game Игровой пакет, благодаря которому можно достаточно легко создавать игры для мобильных устройств.
2.6.1. Класс GameCanvas Абстрактный класс, содержащий основные элементы игрового интерфейса. Конструктор О protected GameCanvas (boolean suppressKeyEvents) -Конструктор абстрактного класса GameCanvas. Методы G void flushGraphics ( ) — копирует изображение из внеэкранного буфера на экран; Q void flushGraphics(int x, int y, int width, int height).копирует изображение из внеэкранного буфера на экран в заданный по размеру прямоугольник; О protected Graphics getGraphics ( ) - получает графические элементы для представления их в последствии классом GameCanvas; Р int getKeyStates ( ) - определяет, какая из клавиш нажата; Q void paint (Graphics g) - рисует графические элементы, представленные классом GameCanvas.
Справочник по Java 2 Micro Edition
2.5.26. Класс TextField Создает редактируемый текстовый контейнер, который встраивается в класс Form. Конструктор О TextField (String label, String t e x t , int maxSize, int constraints) — создает текстовый контейнер с заданным заголовком, строкой текста, максимальным размером символов и ограничением, с последующей интеграцией в класс Form. О void delete (int o f f s e t , int length) - удаляет все символы из созданного контейнера; О int getCaretPosition( ) - получает текущую позицию нахождения указателя на экране; О int getChars (char [] data) - копирует содержимое контейнера TextField- в массив данных; Q int getConstraints ( ) - получает текущие ограничения для контейнера; Q int getMaxSize ( ) - возвращает максимальное число символов, установленное для контейнера TextField; Q String g e t S t r i n g O - получает строку текста из содержимого контейнера TextField; О void insert (char [] data, int o f f s e t , int length, int position) - вставляет массив символов в TextField; Q void insert (String src, int position) - вставляет строку текста в TextField; Q void -setChars (char [] data, int o f f s e t , int length) -прописывает в TextField массив символов; О void setConstraints (int constraints) - устанавливает ограничения; Q void setlnitiallnputMode (String characterSubset) -задает напоминание; Q int setMaxSize ( int maxSize) - устанавливает максимальный размер для TextField; G void setString (String text) - прописывает в TextField строку текста; Q int size ( ) - определяет размер TextField. Константы Q static int ANY - определяет ввод любого текста; Q s t a t i c int CONSTRAINT_MASK - режим ограничения для маски; Q static int DECIMAL — ввод дробных числовых значений; Q s t a t i c int EMAILADDR - используется при вводе электронного адреса; О static int INITIAL_CAPS_SENTENCE - начальный символ каждого предложения будет печататься с заглавной буквы;
Пакет javax.microedition.lcdui
JliBBHIHEIQ
Методы ГЛ int getAppearanceMode ( ) - возвращает заданный способ отображения текста на экране; Q Font g e t F d n t ( ) - получает шрифт текста; О String getTextO - получает текст для класса String I tern; Q void setFont(Font f o n t ) - устанавливает шрифт текста; G void s e t P r e f e r r e d S i z e ( i n t width, int .height) — задает ширину и высоту текста; Q void setText (String t e x t ) - устанавливает текст для класса Stringltem.
2.5.25. Класс TextBox Организовывает редактируемый текстовый контейнер. Конструктор Q TextBox(String t i t l e , String text, int maxSize, int constraints) - создает текстовый контейнер с заданным заголовком, строкой текста, максимальным размером символов и ограничением. Методы ЕЗ void delete (int o f f s e t , int length) - удаляет все символы из созданного контейнера; Q int getCaretPosition() - получает текущую позицию нахождения указателя на экране; Q int getChars (char [ ] data) - копирует содержимое контейнера TextBox в массив данных; О int getConstraints ( ) — получает текущие ограничения для контейнера; Q int getMaxSize ()-возвращает максимальное число символов, установленное для контейнера TextBox; Q String getStringO - получает строку текста из содержимого контейнера TextBox; Q void i n s e r t ( c h a r [ ] data, int o f f s e t , int . l e n g t h , int position) - вставляет массив символов в TextBox; Q void insert (String src, int position) - вставляет строку текста в TextBox; Q void setChars(char[] data, int o f f s e t , int l e n g t h ) - п р о п и сывает в TextBox массив символов; . G void setConstraints (int constraints) — устанавливает ограничения; devoid s e t l n i t i a l l n p u t M o d e ( S t r i n g characterSubset) -задает напоминание; Q int setMaxSize (int m a x S i z e ) - устанавливает максимальный размер для TextBox; Q void setString( String text) - прописывает в TextBox строку текста; Q.void setTicker (Ticker ticker) - устанавливает бегущую строку; Q void setTitle (String s) - устанавливает заголовок; Q int s i z e ( ) - определяет размер TextBox.
Справочник по Java 2 Micro Edition void s e t F i t P o l i c y ( i n t f i t P o l i c y ) - устанавливает привилегированную позицию; Q void setFont(int elementNum, Font font) - устанавливает шрифт заданному элементу в списке; d void setSelectCommand (Command command) - этот метод предназначен для работы с типом IMPLICIT; Q void setSelectedFlags(boolean[] selectedArray)-устанавливает состояние выбранных элементов; G void setSelectedlndex(int elementNum, boolean selected) устанавливает индекс выбранного элемента в списке; Q void setTicker (Ticker ticker) - устанавливает бегущую строку; Q void setTitle (String s) - добавляет название; Q int size ( ) - с помощью этого метода можно узнать количество элементов в списке. Константа Q static Command SELECT_COMMAND - команда по умолчанию для типа IMPLICIT.
2.5.22. Класс Screen Суперкласс для всех высокоуровневых классов определяющих пользовательский интерфейс приложения.
2.5.23. Класс Spacer Создает заданное пространство на экране. Конструктор О Spacer (int minWidth, int minHeight) - создает пространство на экране с заданной шириной и высотой. г Методы Q void addCommand(Command cmd) - добавляет команду; Q. void setDefaultCommand(Command cmd) - устанавливает команду по умолчанию; Q void setLabel (String label) - устанавливает метку; Q'void setMinimumSize(int minWidth, int minHeight) -устанавливает минимальный размер для создаваемого пространства.
2.5.24. Класс Stringltem Формирует текстовые строки. Конструкторы Q Stringltem (String label, String text) - создает строку текста с заданной меткой; Q Stringltem(String label, String text, int appearanceMode) - создает строку текста с заданной меткой и режимом отображения.
Пакет javax.microedition.lcdui Q Q Q 13 О Q Q •
static in.t LAYOUT_NEWLINE_AFTER - размещение на новой строке; static int LAYOUT_NEWLINE_BEFORE - размещение в начале строки; static int LAYOUT_RIGHT - выравнивание по правой стороне экрана; static int LAYOUT_SHRINK - уменьшение компонента по ширине; static int LAYOUT_TOP - выравнивание по верхней стороне экрана; static int LAYOUT_VCENTER - выравнивание по центру экрана; static int LAYOUT_VEXPAND - увеличение высоты для размещения компонента; О static int LAYOUT_VSHRINK - уменьшение высоты для размещения компонента; Q static int PLAIN - установка режима появления первого плана для компонента.
2.5.21. Класс List Создает список группы элементов. Конструкторы Q List (String title, int listType) - формирует список с названием и типом созданного списка; О List(String t i t l e , int listType, S t r i n g [ ] v s t r i n g E l e m e n t s , Image [ ] imageElements) - формирует список с названием, типом созданного списка, массивом строк и изображений для списка элементов. Методы О int append(String stringPart, Image imagePart)-добавление списка элементов; CD void delete (int elementNum) - удаление заданного элемента из списка; Q void deleteAllO - удаление всех элементов из списка; Q int getFitPolicyO - получает привилегированную позицию; Q Font getFont(int elementNum) - получает шрифт для заданного элемента в списке; Q Image getlmage(int elementNum) - получает изображение для заданного элемента в списке; О int getSelectedFlags(boolean[] selectedArray_return) возвращает состояние всех элементов в виде массива данных; Q int getSelectedlndex() - получает выбранный индекс элемента в списке; Q String getString (int elementNum) — получает строку текста для выбранного элемента из списка; Q void insert(int elementNum, String stringPart, Image imagePart ) - вставляет элемент в список до указанного номера элемента в списке. U boolean isSelectedfint elementNum) - получает выбранный элемент из списка; Q void removeCommand (Command cmd) - удаляет команду для списка; Q void s e t ( i n t elementNum, String stringPart, Image imagePart ) — вставляет новый элемент в список взамен предшествующего;
Справочник по Java 2 Micro Edition Методы Q String get Al tText ()'-размещает текст; Q int get AppearanceMbde ( ) - возвращает режим представления; Q Image getlmage ( ) - получает изображение; Q int getLayout ( ) - получает директивы для размещения изображенищ О void set AltText (String text)—устанавливает дополнительный текст; О void setlmage(Image img) - устанавливает изображение; Q void setLayout(int layout) -устанавливает директивы для размещения изображений.
2.5.20. Класс Item Суперкласс, содержащий ряд классов для их дальнейшей интеграции в класс Form. Методы Q void addCommand(Command cmd) - добавляет команду; О String getLabel ( ) - получает метку объекта Item; Q int getLayout ( ) - использует директивы для размещения компонентов в форме; О int getMinimumHeight ( ) - получает минимальную высоту; Q int getMinimumWidth() - получает минимальную ширину; Q int getPreferredHeight ( ) - получает предпочтительную высоту; Q int getPref erredWidth ( ) - получает предпочтительную ширину; Q void notifyStateChanged() - компонент, содержащийся в форме. Уведомляет объект ItemStateListener о своем состоянии; Q void removeCommand (Command cmd) - удаляет команду из компонента. Q void setDefaultCommand (Command cmd) - встроенная команда по умолчанию для данного компонента; Q void setltemCommandListener (ItemCommandListene-r 1) -устанавливает обработку событий для компонента; О void setLabel (String label) - устанавливает назначенную метку для компонента; Q void setLayout (int layout) - устанавливает рассмотренные выше директивы для форматирования компонента; Q void setPref erredSize (int width, int height) -устанавливает оптимальную высоту и ширину компонента. Константы Q static int Q static int Q static int Q static int Q static int Q static int Q static int Q static int
BUTTON - отображение элемента в виде кнопки; HYPERLINK - отображение элемента в виде гиперссылки; LAYOUT_2 - режим установки; LAYOUT_BOTTOM - выравнивание по нижней стороне экрана; LAYOUT_CENTER - выравнивание по центру экрана; LAYOUT_DEFAULT - значение по умолчанию; LAYOUT_EXPAND - увеличение ширины компонента; LAYOUT_LEFT - выравнивание по левой стороне экрана;
Пакет javax.microedition.lcdui Q static int TOP - верхняя линия привязки шрифта; Q static int VCENTER - выравнивает по центру изображение.
2.5.18. Класс Image Отвечает за загрузку и отображение любых видов графических изображений формата PNG. Методы О s t a t i c Image createlmage(byte[] imageData, int imageO f f s e t , int imageLength) - загружает изображение, учитывая смещение и длину в байтах; О s t a t i c Image createlmage (Image source) - загружает изображение из файла; Q static Image createlmage(Image image, int x, int y , int width, int height, int transform) - загружает изображение в заданное место, определенное координатами с возможностью трансформации изображения; Q static Image createlmage (InputStream stream) -загружает изображение из потока; О static Image createlmage(int width, int height) -загружает изображение в заданные размеры;' Q static Image createlmage (String name) - загружает изображение из ресурса; Q static Image createRGBImage(int[] rgb, int width, int height, boolean processAlpha) - загружает изображение, учитывая цветовую компоненту ARGB; Q Graphics getGraphics() — создает графический объект Для представления изображения; О int getHeightO -• получает высоту изображения; Q void g e t R G B ( i n t [ ] rgbData, int o f f s e t , int .scanlength, int x, int y , int width, int height) - получает цвет в представлении ARGB и сохраняет в массиве данных; О int getWidth ( ) - получает ширину изображения; О boolean isMutable ( ) ' - проверяет изображение.
2.5.19. Класс Imageltem Контейнер для загружаемых в приложение сложных графических изображений Конструкторы Q Imageltem(String label, Image img, int layout, String altText) — создает объект класса Imageltem с заданной меткой, изображением, размещением и дополнительной строкой текста; Q Imageltem(String label, Image image, int layout, String altText, int appearanceMode) - создает объект класса Imageltem с заданной меткой, изображением, размещением, дополнительной строкой текста, и режимом представления.
Справочник по Java 2 Micro Edition О void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) - рисует заполненный прямоуголь1 ник, используя закругленные углы; О void f illTriangle (int xl, int y l , int x2 , int y2 , int. x3 , int y3 ) - рисует заполненный цветом треугольник; О int getBlueComponent ( ) - получает синий компонент цвета; О int getClipHeight ( ) - получает высоту для текущей области отсечения; Q int getClipWidtht) - получает ширину для текущей области отсечения; О int getClipX()-получает координату по оси X для текущей области отсечения; Q int getClipY ( ) - получает координату по оси Y для текущей области отсечения; Q int getColor () - получает текущий цвет; СЭ int getDisplayColor (int color) - получает цвет для отображения; Q Font getFontO - получает текущий шрифт; Q int getGrayScale ( ) - получает значение полутонов; Q int getGreenComponent ().- получает зеленный компонент цвета; Q int getRedComponent ( ) - получает красный компонент цвета; Q int getStrokeStyle ()—получает используемый штриховой стиль; Q int getTranslateX() - получает координату по оси X для перемещен/ ного контекста; Q int getTranslateY()- получает координату по оси Y для перемещенного контекста; Q void setClip(int x, int y, int width, int height) —устанавливает отсечение заданной области экрана; Q void setColor(int RGB) - устанавливает цвет при помощи значения RGB; Q void setColor(int red, int green, int blue) - назначает цвет при помощи трех цветовых компонентов red, green и blue; Q void setFont (Font font) - устанавливает заданный шрифт; Q void setGrayScale (int value) - задает значение полутонов; Q void setStrokeStyle (int style) - задает штриховой стиль рисуемому контексту, используя Константы SOLID и DOTTED; Q void translate (int x, int у) - перемещает систему координат в точку (х, у). Константы Q static int BASELINE - опорная линия привязки шрифта; Q static int BOTTOM - нижняя линия привязки шрифта; Q static int DOTTED - пунктирный стиль; Q static int HCENTER - центральна линия привязки шрифта; Q static int LEFT - левая сторона привязки шрифта; Q static int RIGHT - правая сторона привязки шрифта;' Q static int SOLID - штриховой стиль;
Пакет javax.microedition.lcdui Q static int INDEFINITE - максимальное значение с неопределенным диапазоном работы.
2.5.17. Класс Graphics Предоставляет возможность рисования графических элементов на экране мобильного устройства. Методы Q void clipRect (int x, int y, int width, int height) -отсекает заданный прямоугольник; . О void copyAreafint x_src, int y_src, int • w i d t h , int height, int x_dest, int y_dest, int anchor) - копирует прямоугольную область из установленных значений в параметрах x_src, y_src, width, height, в новую область x_dest, y_dest; Q void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) - рисует контур дуги в виде эллипса; Q void drawChar(char character, int x, int y, int anchor) рисует символ; Q void drawChars(char[] data, int o f f s e t , int length, int x, int y, int anchor) - рисует массив символов; Q void drawlmage (Image img, int x, int y , int anchor) рисует изображение; Q void drawLine(int x l , int y l , int x2 , int y 2 ) —рисуетлинию из точки xl и yl до точки х2 и у2; С] void drawRegion (Image src, int x_src, int y_src, int width, int height, int transform, int x_dest, int y_dest, int anchor) - копирует изображения в заданную область на экран телефона; .Q void drawRGB(int[] rgbData, int o f f s e t , int scanlength, int x, int y, int width, int height, boolean processAlpha) — получает цвет в представлении ARGB и сохраняет в массиве данных; Q void drawRoundRect(int x, int у , ' int width, int height, int arcWidth, int a r c H e i g h t ) - рисует контур прямоугольника, используя закругленные углы; Q void "drawstring (String str, int x, int y, int anchor) рисует строку текста с заданным цветом и размером шрифта; О void drawSubstring(String str, int o f f s e t , int len, int x, int y, int anchor) - рисует подстроку текста с заданным цветом и размером шрифта; Q void f i l l A r c ( i n t x, int y, int width, int height, int startAngle, int arcAngle) - рисует заполненную цветом дугу; Q void f i l l R e c t ( i n t x, int y, int width, int height) -рисует заполненный цветом прямоугольник;
Справочник по Java 2 Micro Edition Q void set(int itemNun), Item item) - устанавливает компонент, ссылающийся на компонент itemNum, заменяя при этом предшествующий компонент; Q void setltemStateListener (ItemStateListener iListener) устанавливает переменную iListener для формы, заменяя при этом предыдущую переменную iListener; О int size () - получает количество компонентов в форме.
2.5.16. Класс Gauge Представляет графическое течение процесса, своего рода датчик или счетчик. Конструктор Q. Gauge(String label, boolean interactive, int maxValue, int initialValue) - создает графическое течение процесса с заданной меткой, режимом и максимальным и минимальным значением в работе. Методы . .' Q void addCommand (Command cmd) — добавляет команду; Q int getMaxValue ()-получает значение максимального диапазона работы процесса; О int getValue ()-получает текущее значение в процессе работы; О boolean islnteractive ( ) — определяет возможность изменения установленного счетчика; Q void setDefaultCommand (Command cmd) - задает команду по умолчанию для компонентов Item; Q void setltemCommandListener(ItemCommandListener 1)-устанавливает обработчик событий; Q void setLabel (.String label) -устанавливает метку для элемента; Q void setLayout (int layout) - устанавливает директивы для элемента; Q void setMaxValue (int maxValue) - устанавливает максимальное значение течение процесса; Q void setPreferredSize(int width, int height) -задаетширину и высоту для графического представления всего течения процесса; О void setValue(int value) - устанавливает текущее значение процесса. Константы Q static int CONTINUOUS_IDLE - непрерывное и неактивное состояние с неопределенным диапазоном работы; Q static int CONTINUOUS_RUNNING - непрерывное активное состояние с неопределенным диапазоном работы; Q static int INCREMENTAL_IDLE - увеличивающееся и неактивное состояние с неопределенным диапазоном работы; Q static int INCREMENTAL_UPDATING - увеличивающееся и постоянно модифицируемое состояние с неопределенным диапазоном работы;
Пакет javax.microedition.lcdui Q boolean isPlainO - возвращает значение true, если используется 1 Plain; ' Q boolean isUnderlined() -возвращаетзначение true,если используется Underlined; Q int stringWidth (String str) - устанавливает строку текста; Q int substringWidthfString str, int o f f s e t , int len) -устанавливает подстроку текста. Константы Q s t a t i c int FACE_MONOSPACE - шрифт с небольшим интервалом; Q s t a t i c int FACE_PROPORTIONAL - пропорциональный шрифт; О s t a t i c int FACE_SYSTEM - системный шрифт; Q static int FONT_INPUT_TEXT - текст ввода; G static int FONT_STATIC_TEXT - заданный по умолчанию шрифт; Q static int SI ZE_LARGE-большой шрифт; Q static int SIZE_MEDIUM - средний шрифт; , Q static int SIZE_SMALL -маленький шрифт; Q static, int STYLE_BOLD - жирный шрифт; О static int STYLE_ITALIC - курсив; Q static int STYLE_PLAIN - обычный шрифт; Q static int STYLE_UNDERLINED - подчеркнутый шрифт.
2.5.15. Класс Form Этот класс создает пустую форму, в которую интегрируются классы пользовательского интерфейса. Конструкторы Q Form (String t i t l e ) - создает новую пустую форму; О Form (String t i t l e , Item[] items) - создает новую форму с заданным заголовком и установленными компонентами класса 11 em. Методы G int append (Image img) — добавляет в форму одно изображение; Q int append (Item item) - этот метод добавляет любой из доступных компонентов класса Item в созданную форму; Q int append (String str) -добавляете форму строку; Q void delete (int itemNum) - удаляет компонент ссылающийся на itemNum; G void deleteAll () - удаляет все компоненты с имеющейся формы; G Item get (int itemNum) - получает позицию выбранного компонента; Q int getHeight ( ) - возвращает высоту экрана в пикселях доступную для встраиваемых компонентов; G int getWidth () - возвращает ширину экрана в пикселях доступную для встраиваемых компонентов; Q void insert (int itemNum, Item item) - вставляет компонент в форму до определенного компонента;
Справочник по Java 2 Micro Edition
2.5.13. Класс Displayable Абстрактный класс, содержит иерархию классов пользовательского интерфейса. Методы G void addCoiranand (Command cmd) - добавляет команду; Q int getHeight ( ) - получает высоту доступной области экрана в пикселях; Q Ticker getTicker ( ) - получает бегущую строку; Q String getTitleO - получает заголовок; Q int getWidth() -получает ширину доступной области экрана в пикселях; Q boolean is Shown О - проверяет видимость объекта на экране; Q void removeCommand (Command cmd) - удаляет команду; Q void setCommandListener(CommandListener 1) —устанавливает обработчик событий; Q-void setTicker (Ticker ticker) - устанавливает бегущую строку; . Q void setTitle (String s) - устанавливает заголовок; Q protected void sizeChanged(int w, int h) - изменяет видимую область дисплея.
2.5.14. Класс Font Класс шрифтов. Методы ~Q int charsWidth(char[] ch, int o f f s e t , int length)-применяется для правильного планирования использования шрифта на экране дисплея; Q int charWidth(char ch) - получает ширину шрифта; Q int getBaselinePosition() - вычисляет расстояние от верхней кромки текста до опорной позиции в пикселях; Q static Font getDefaultFont ( ) • - получает системный шрифт, используемый устройством по умолчанию; Q int getFace ( ) — получает начертание шрифта используемого устройством по умолчанию; Q static Font getFont(int fontSpecif ier) - используется классом Customltem для получения специального шрифта; Q static Font getFont(int f a c e , int style, int s i z e ) - п о л у чает шрифт с указанием начертания, стиля и размера; Q int getHeight ( ) - получает высоту шрифта; Q int getSize ()-получает размер шрифта; Q int getStyleO - получает стиль шрифта; Q boolean isBoldO - возвращает значение true, если используется Bold; Q boolean i s l t a l i c ( ) - возвращает значение true, если используется italic;
Пакет javax.microedition.lcdui Методы 'О void callSerially (Runnable r) - производит запрос на вызов метода run ( ) для объекта класса Runnable; О boolean f lashBacklight (int duration) -создает эффект подсветки; HI int getBestlmageHeight (int imageType) - получает оптимальную высоту для изображения на экране; О int getBest!mageWidth(int imageType) - получает оптимальную ширину для изображения на экране; О int getBorderStyle (boolean highlighted) - штриховой стиль бордюра; Q int getColor(int colorSpecifier) - возвращает цвет; Q Displayable getCurrent ( ) - получает текущий объект Displayable для используемого мидлета; О static Display getDisplay (MIDlet m) - получает уникальный объект Display для используемого мидлета; Q boolean isColor ( ) — получает информацию о поддержке цвета в мобильном устройстве; О int numAlphaLevels() - получает количество альфа-прозрачных уровней; О int numColors (.) - получает количество цветов поддерживаемых мобильным устройством; Q void setCurrent(Alert alert, Displayable 'nextDisplayable) - делает видимым на экране объект класса Alert; G void setCurrent(Displayable nextDisplayable) ,—делает видимым на экране последующий объект класса Displayable; Q void setCurrentltem(Item item) - делает видимым на экране объект класса Item; Q boolean vibrate (int duration) - запрос на поддержку вибрации. Константы Q s t a t i c int ALERT-тип изображений для уведомлений; Q static int CHOICE_GROUP_ELEMENT - тип изображения для класса ChoiceGroup; • Q static int -COLOR_BACKG-ROUND — цветовой компонент, используется методом getColor ( ) ; Q static int COLOR_BORDER - цветовой компонент, используется методом getColor() ; Q static int COLOR_FOREGROUND - цветовой компонент, используется методом getColor ( ) ; •Q static int COLOR_HIGHLIGHTED_BACKGROUND - цветовой компонент, используется методом getColor ( ) ; Q static int COLOR_HIGHLIGHTED_BORDER - цветовой компонент, используется методом getColor ( ) ; Q static int COLOR_HIGHLIGHTED_FOREGROUND - цветовой компонент, используется методом getColor ( ) ; О! s t a t i c int LIST_ELEMENT - тип изображения для класса List.
Справочник по Java 2 Micro Edition Q protected void repaint () - перерисовывает экран; Q protected void repaint (int x, int y, int w, int h) перерисовывает заданную область экрана; Q protected void showNotifyO - уведомление о возможности получения действий; Q protected void sizeChanged(int w, int h)-- изменяет размер. Константы Q protected static int KEY_PRESS - нажатие клавиши; Q protected static int KEY_RELEASE - отпускание клавиши; Q protected static int KEY_REPEAT - повторное нажатие клавиши; Q protected static int NONE - нет действий; Q protected static int POINTER_DRAG - перетаскивание; Q protected static int POINTER_PRESS -указательнажат; Q protected static int POINTER_RELEASE - указатель отпущен; Q protected static int TRAVERSE_HORIZONTAL - горизонтальный обход; О protected static int TRAVERSE_VERTICAL - вертикальный обход.
2.5.11. Класс Date Field Класс, представляющий работу с датой и временем. Интегрируется в класс Form, наследуется от класса Item. Конструкторы Q DateField(String label, int mode) - создает объект класса DateField, с указанием метки и режима отображения объекта; Q DateField(String label, int mode, TimeZone timeZone) — создает объект класса DateField, с указанием метки, режима отображения объекта и часового пояса. Методы Q Date getDateO - возвращает текущую дату; Q void setDate(Date date) - устанавливает новую дату; Q int getlnputMode () - получает установленные компоненты DATE, TIME ИЛИ DATAJTIME; Q void setlnputMode(int mode) - устанавливает компоненты DATE, TIME ИЛИ DATE_TIME.
Константы Q static int DATE-дата; Q static int DATE_TIME - дата и время; Q static int TIME - только время.
2.5.12. Класс Display Менеджер дисплея определяющий, какой из объектов будет представлен на дисплее.
Пакет jovax.microedition.lcdui Р static int HELP - помощь; О static int ITEM - новый экран, ассоциирующийся с экраном от которого происходит переход; Р static int OK - хорошо; Р static int SCREEN - новый-экран; P s t a t i c int STOP - стоп.
2.5.10. Класс Custom Item Создает возможность в отображении новых графических элементов встроенных в класс Form. Конструктор Р protected Customltem( String label) - Конструктор абстрактного класса Customltem. Методы Р int getGameAction (int keyCode)-получает игровые действия по коду клавиши телефона; Р protected int getlnteractionModes() - получает все доступные режимы взаимодействия; Р protected abstract int getMinContentHeight() -получаетминимальную высоту заданной области дисплея; Р protected abstract int getMinContentWidth() - получает минимальную ширину заданной области дисплея; Р protected abstract int getPrefContentHeight(int width) получает предпочтительную высоту заданной области дисплея; Р protected.abstract int getPrefContentWidth(int height) получает предпочтительную ширину заданной области дисплея; Р protected void hideNotify ( ) - уведомляет о недоступности; Р protected void invalidate () — сигнализирует об изменении размера или местонахождения элемента; Р protected void keyPressed(int key'Code)-обрабатывает нажатие клавиши; Р protected void keyReleased(int keyCode) - обрабатывает отпускание клавиши; Р protected void keyRepeatedfint keyCode) - обрабатывает повторное нажатие клавиши; Q protected abstract void paint(Graphics g, int w, int h ) рисует компоненты; P protected void pointerDragged(int x, int у) - осуществляет поддержку перьевого ввода; Р protected void pointerPressed(int x, int у) - в месте установки указателя были произведены действия по нажатию определенной клавиши; Р protected void point erReleased( int x, int у) - вместе установки указателя были произведены действия по отпусканию нажатой клавиши;
Справочник по Java 2 Micro Edition О int getSelectedlndex ( ) - возвращает индекс выбранного элемента группы; Q String g e t S t r i n g ( i n t elementNum) - получает строку текста по номеру; . Q void insert(int elementNum,String stringPart,Image imagePart) - вставляет элемент в группу; Q boolean isSelected(int elementNum) - получает выбранную логическую величину; Q void set(int elementNum, String . stringPart, Image imagePart). - устанавливает текст и изображение в заданный элемент группы; при этом удаляя предыдущую запись; Q void setFitPolicy ( i n t f i t P o l i c y ) - устанавливает предпочтительную экранную позицию; О void setFont(int elementNum, Font font) — устанавливает шрифт заданному элементу; О void setSelectedFlags (boolean[]• selectedArray) —устанавливает состояние элементов группы; Q void setSelectedlndex(int elementNum, boolean selected) устанавливает особое состояние для элемента группы при использовании множественного типа; Q int size ( ) - возвращает количество используемых элементов группы.
2.5.9. Класс Command Инкапсулирует командные действия, при этом не определят фактические действия на команды, а лишь содержит информацию. Конструкторы Q Command(String label, int commandType, int priority) создает команду для дальнейшей обработки. Команда содержит: название, тип и приоритет выполнения; Q Command(String shortLabel, String longLabel, int commandType, int priority) - создает команду для дальнейшей обработки. Команда содержит: короткое и длинное название, тип и приоритет выполнения. Методы О int get CommandType ( ) - получает тип используемой команды; Q String getLabel ( ) - получает метку или название команды; О String getLongLabel ( ) - получает длинную метку или название команды; Q int getPriority ()-получает установленный приоритет команды. Константы Q static int BACK-назад; Q static int CANCEL - отмена; Q static int EXIT - выход;
Пакет javax.microedition.lcdui О static О static Q static О static Q static Q static Q static Q static Q static Q static Q static Q static •a static Q static Q static Q static О static Q static Q, static
int GAME_A - игровая клавиша А; int GAME_B - игровая клавиша В; int GAME_C - игровая клавиша С; int GAME_D - игровая клавиша D; int KEY_NUMO - клавиша 0; int KEY_NUM1-клавиша 1; int KEY_NUM2 - клавиша 2; int KEY_NUM3 - клавиша3; int KEY_NUM4 - клавиша4; int KEY_NUM5 - клавиша 5; int KEY_NUM6 - клавиша 6; int KEY_NUM7 - клавиша7; int KEY_NUM8 - клавиша 8; int KEY_NUM9 - клавиша 9; int KEY_POUND - клавиша #; int KEY_STAR - клавиша *; int LEFT - движение влево; int RIGHT - движение вправо; int UP - движение вверх.
2.5.8, Класс ChoiceGroup Встраиваемая группа выбираемых элементов. Интегрируется в класс Form, наследуется от класса Item и реализует интерфейс Choice. Конструктор Q ChoiceGroup (String label, int choiceType) - создает пустой список элементов группы, определяя заголовок и тип группы элементов; Q ChoiceGroup(String label, int choiceType, String[] stringElements, Image [] imageElements) - создает группу элементов, определяя заголовок, тип группы элементов, текст и изображение для каждого элемента группы. Методы Q int append (String stringPart, Image imagePart) -добавляет, элемент в группу; О void delete (int elementNum) - удаляет заданный элемент из группы; О void deleteAlK) - удаляет все элементы; Q int getFitPolicy ( ) — предоставляет предпочтительную экранную позицию; Q Font getFont(int elementNum) - получает используемый шрифт элемента группы; Q Image getlmage(int elementNum) - получает изображение для элемента группы; Q int getselectedFlags(boolean[]selectedArray_return) -воз: вращает значение Boolean для группы элементов;
Справочник по Java 2 Micro Edition Методы Q int getGameAction (int keyCode) - связывает игровые действия с заданным ключевым кодом; Q int getKeyCode (int gameAction) -получает ключевой код игровых действий; Q String getKeyName (int keyCode) - получает ключевой код для клавиши; Q boolean hasPointerEvents ( ) - проверяет устройство на поддержку работы с указателем; G boolean hasPointerMotionEvents ( ) - проверяет поддержку устройством перемещения указателя; . . Q boolean hasRepeatEvents () - проверяет устройство на поддержку работы с повторными событиями; Q protected void hideNotifyO - выполняет запрос после удаления объекта класса Canvas с дисплея; О boolean isDoubleBuf fered( ) - осуществляет двойную буферизацию; Q protected void keyPressed(int keyCode) - вызывается при нажатии клавиши; Q protected void keyReleased(int keyCode) - вызывается при отпускании нажатой клавиши; >, Q protected void keyRepeated( int keyCode) - повторное нажатие клавиши; Q protected abstract void paint (Graphics g) - прорисовка или рендеринг графики на экране телефона; О protected void pointerDragged(int x, int у) —определяет перемещение курсора; Q protected void pointerPressed(int x, int у) -определяет позицию курсора, в которой должно производится нажатие определенной клавиши; Q. protected void pointerReleasedf int x, int у ) - определяет позицию курсора в момент отпускания определенной клавиши; Q void repaint () - повторяет прорисовку; G void repaint (int x, int у, int width, int height) —повторяет прорисовку заданной области; Q void serviceRepaints ( ) - повтор прорисовки дисплея; \ О void setFullScreenMode (boolean mode) - контроль над полноэкранным режимом отображения; Q protected void showNotifyO - выполняет запрос до вывода объекта класса Canvas на дисплей; Q protected void sizeChanged(int w, 'int h) - изменяет размер. Константы Q static int DOWN - движение вниз; Q static int FIRE - обычно используется в играх и реализует стрельбу из оружия;
Пакет javax.microedition.lcdui
1
Q int getDef aultTimeout ( ) - получает время для представления уведомления; Q Image get Image () - получает изображение для экрана, представленного классом Alert; Q Gauge getlndicator ( ) - этот метод позволяет воспользоваться графическим измерителем класса Gauge; 01 String getStringO - получает текстовую строку; , Q int getTimeout ( ) - получает заданное время для представления уведомления; Q AlertType getTypeO - определяет тип используемого уведомления; Q void removeCommand (Command cmd) - удаляет команду; Q void setCommandListener (CommandListener 1) - устанавливает обработчик событий;! Q void set Image (Image i m g ) - устанавливает изображение; Q void setlndicator (Gauge indicator) - устанавливает индикатор измерителя для использования класса Gauge; Q void setstring (String str) — устанавливает строку текста; Q void setTimeout (int time) - устанавливает время; Q void setType (AlertType type) - устанавливает тип уведомлений или информационных сообщений. Константы U static Command DISMISS_CQMMAND - команда отклонена; Q static int FOREVER - определяет постоянный показ уведомления.
2.5.6. Класс AlertType Отображает тип уведомления. Конструктор Q protected AlertType () - закрытый Конструктор подкласса. Метод Q boolean playSound( Display display) - воспроизводит звук. Константы Q static AlertType ALARM - тревога; Q static AlertType CONFIRMATION - подтверждение; Q static AlertType ERROR - ошибка; Q static AlertType INFO - информация; Q static AlertType WARNING - предупреждение.
2.5.7. Класс Canvas Абстрактный класс, обеспечивающий графическую прорисовку различных элементов на экране телефона. Конструктор Q protected Canvas () - создает новый объект класса Canvas.
Справочник по Java 2 Micro Edition Q int size ( ) - определяет количество элементов в наборе элементов. Константы Q static int EXCLUSIVE - эксклюзивный выбор; Q static int IMPLICIT - неявный выбор; Q static int MULTIPLE — множественный выбор; О static int POPUP - всплывающий вид выбора; О static int TEXT_WRAP_DEFAULT - текстовое сопровождение элемента будет находиться по умолчанию; Q static int TEXT_WRAP_OFF - текстовое сопроврждение элемента должно находится на одной строке; Q static int TEXT_WRAP_ON - текстовое сопровождение элемента находится на любом количестве строк.
2.5.2. Интерфейс CommandListener Реализует возможность обработчика событий. Метод Q void commandAction(Command с, Displayable d) -обработчик событий.
2.5.3. Интерфейс ItemCommandListener Реализует возможность получения событий от объектов класса Item. Метод О void commandAction (Command с, Item item) - обработчик событий.
2.5.4. Интерфейс ItemStateListener Используется при получении событий о состоянии объектов класса Item встроенных в Form. Метод Q void itemStateChangeddtem item) - определяет состояние объекта класса Item.
2.5.5. Класс Alert Создает различные информационные сообщения. . , Конструкторы Q Alert (String t i t l e ) - создает пустое уведомление с заголовком; Q Alert(String title, String alertText, Image alertlmage, AlertType alertType) - создает уведомление с заголовком, текстом, изображением и типом уведомления. Методы О void addCommand( Command cmd) -добавляет команду;
Пакет javax.microeditibn.lcdui
2.4.19. Исключение О ConnectionNotFoundException - указывает на отсутствие связи.
2.5. Пакет javax.microedition.lcdui Пакет классов пользовательского интерфейса (UI) для создания полей, форм, уведомлений, текста и так далее.
2.5.1. Интерфейс Choice Содержит набор методов создающих возможность выбора заданных элементов Методы Q int append(String s t r i n g P a r t , Image imagePart) -добавляет элемент к набору элементов в конец всего имеющегося списка элементов; Q void delete (int elementNum) - удаляет элемент по заданному номеру; О -void deleteAll ( ) - удаляет все элементы; • Q int getFitPolicy ( ) - предоставляет предпочтительную экранную позицию; Q Font g e t F o n t f i n t elementNum) - получает шрифт для элемента заданного по номеру; Q Image getlmage (int elementNum) - получает изображение для элемента заданного по номеру; О int getSelectedFlags(boolean[] selectedArray_return) производит запрос на состояние элементов массива; Q int getSelectedlndex ( ) - получает выбранный*индекс элемента; Q String getString (int elementNum) - получает строку текста по заданному номеру; О void insert (int elementNum-, String stringPart, Image imagePart) - производит вставку элемента по заданному номеру в набор имеющихся элементов; Q boolean i s S e l e c t e d f i n t elementNum) -получает логическое значение, определяющее выбор того или иного элемента из набора элементов; G void s e t ( i n t elementNum, String s t r i n g P a r t , Image imagePart ) - устанавливает новую строку текста с изображением по заданному номеру, заменяя предыдущую запись; Q void setFitPolicy (int fitPolicy) - устанавливает предпочтительную экранную позицию; Q void s e t F o n t ( i n t elementNum, Font f o n t ) - устанавливает шрифт для заданного элемента; Q void setSelectedFlags (boolean:'[] selectedArray) -устанавливает состояние элементов массива; Q void setSelectedlndex (int; elementNum, boolean selected) устанавливает состояние элемента;
Справочник по Java 2 Micro Edition int getLocalPort ( ) -получает локальный порт связи, с дейтаграммой.
2.4. 77, Класс Connector Класс для создания объектов связи. Методы О static Connection open (String name ) - создает и открывает соединение; G static Connection open(String name, int mode) - создает и открывает соединение по адресу и режиму соединения; Q static Connection open ('String name, int mode, boolean t imeout s ) - создает и открывает соединение по адресу, режиму соедине. ния и исключения времени ожидания связи; G s t a t i c DatalnputStream openData!nputStream.( String name) создает и открывает входной поток данных; Q static DataOutputStream openDataOutputStream (String name ) - создает и открывает выходной поток данных; Q stati-c InputStream open!nputStream( String name) -создает и открывает входной поток; О static OutputStream openOutputStream( String name) -создает и открывает выходной поток. Константы Q static int READ - режим доступа только для чтения данных; Q static int READ_WRITE -режим доступа для чтения4 и записи данных; Q static int WRITE - режим доступа только для записи данных;
2.4. 18. Класс PushRegistry Класс для поддержания списков связей. Методы Q static String getFilter (String connection) - получает заданный фильтр соединения; Q static String getMIDlet (String connection) - получает заданный мидлет (MIDlet) для соединения; Q static String [] listCbnnections (boolean available) - возвращает весь список подключений для комплекта мидлетов (MIDlet suite); Q static long registerAlarm( String midlet, long time) -производит установку времени для запуска приложения; Q static void registerConnection (String connection, String midlet, String f i l t e r ) -производит установку времени для запуска соединения; G static boolean unregisterConnection (String connection) удаляет регистрацию соединения.
Пакет javax.microedition.io Q Certificate getServerCertif icate ( ) - осуществляет возврат сертификата безопасности соединения.
2.4.12. Интерфейс ServerSocketConnection Реализует связь с сервером. Методы О String getLocalAddress () - получает локальный адрес связи с разъемом (socket); Q int getLocalPort () -получает локальный адрес связи с портом.
2.4.13. Интерфейс SocketConnection Находит разъем (socket) для потока связи. Методы 1 • О String get Address () - получает адрес связи; Q String getLocalAddress () - получает локальный адрес связи; О int getLocal Port ( ) - получает локальный порт соединения; Q int get Port ( ) - получает порт соединения; Q int getSocketOption (byte option) - получает необходимую опцию разъема для создания соединения; О void setSocketOption(byte option, int value) —устанавливает необходимую опцию разъема для создания соединения. Константы Q static byte DELAY - опция малого разъема (0); Q static byte KEEPALIVE -опцияподдержкиособенностей разъема(2); Q static byte LINGER — опция ждущего режима обработки вывода данных (1); Q static byte RCVBUF - опция для определенного буфера получения (3); Q static byte SNDBUF - опция для определенного буфера отправки (4).
2.4.14. Интерфейс StreamConnection Этот интерфейс определяет связь с потоком и не имеет методов и констант.
2.4.15. Интерфейс StreamConnectionNotifier Определяет возможность всей связи. Метод О StreamConnection acceptAndOpen ( ) - возвращает разъем сервера, с которым произошло соединение.
2.4.16. Интерфейс UDPDatagramConnection Реализует связь с дейтограммой. Методы О String getLocalAddress ()-получает локальный адрес связи с дейтограммой;
Справочник по Java 2 Micro Edition Q static int HTTP_GONE - затребованный ресурс не найден; Q static int HTTP_INTERNAL_ERROR - неожиданная ошибка на сервере; Q static int H1TP_LENGTH_REQUIRED - отказ от приема запроса.
2.4.7. Интерфейс HttpsConnection Декларирует Методы и Константы для безопасного сетевого соединения. Методы , Q int get Port ( ) - возвращает сетевой номер порта для соединения; Q' Securitylnfo getSecur,ity!nfo() - получает информацию о безопасности связи.
2.4.8. Интерфейс InputConnection Интерфейс для создания входной связи с сетью. Методы О DatalnputStream openData!nputStream() - открывает и возвращает поток ввода данных для конкретного соединения; Q inputStream openlnputstreamf)-открывает и возвращает входной поток для конкретного соединения.
2.4.9. Интерфейс OutputConnection Интерфейс для создания выходной связи с сетью; Методы Q DataOutputStream openDataOutputStream() - открывает и возвращает поток вывода данных для конкретного соединения; Q OutputStream openOutputStream() - открывает и возвращает выходной поток для конкретного соединения.
2.4.10. Интерфейс SecureConnection Определяет безопасную связь с сетью. Метод
Q Securitylnfo getSecurity Info ( ) - получает информацию о безо. пасности связи.
2.4.11. Интерфейс Securitylnfo Имеет в своем составе методы для получения информации сетевой связи. Методы О String getCipherSuite() - возвращает название используемого шифра связи; Q String getProtocolName ( ) - получает имя используемого протокола соединения; Q String getProtocolVersiont.) - получает версию используемого протокола;
Пакет javax.microedition.io О String getHeaderField (String name) -возвращает заголовок файла по названию; О ' l o n g getHeaderFieldDate (String name, long d e f ) -возвращает значение заданного поля для даты; Q int getHeaderFieldlnt (String name, int def)-возвращает значение заданного поля для номера; . Q String getHeaderFieldKey (int n) - получает файл заголовка по ключу; Q String getHost ( ) - возвращает информацию о соединении; Q long getLastModif i e d ( ) - возвращает значение модифицированного заголовка; Q int get Port ( ) ' - возвращает номер порта соединения; Q String getProtocol ( ) — возвращает имя протокола; Q String get-Query О - возвращает запрос на соединение; Q -String getRequestMethod() - определяет текущий метод произведенного запроса; Q String getReguestProperty (String key) - возвращает свойства запроса для соединения; Q int getResponseCode ( ) — возвращает код состояния протокола HTTP; О String getResponseMessage ( ) - возвращает сообщение о коде состояния протокола HTTP; Q String getURLO - возвращает адрес соединения; Q void setRequestMethod (String method) - задает метод для запроса адреса; Q void setRequestProperty(String key, String value) -устанавливает свойства производимого запроса. Константы Q static String GET - метод соединения по протоколу HTTP; Q static String HEAD- основной метод соединения по протоколу HTTP; Q static int HTTP_ACCEPTED - запрос принят, но не был обработан; Q stat ic int HTTP_BAD_GATEWAY - недопустимый ответ от сервера; Q static int HTTP_BAD_METHOD - не позволительный метод для запроса; Q static int HTTP_BAD_REQUEST - запрос не был принят; Q static int HTTP_CLIENT_TIMEOUT - запрос не произведен в момент связи с сервером; Q static int HTTP_CONFLICT - запрос не закончен из-за конфликта; Q static int HTTP_CREATED - запрос'произведен; Q static int HTTP_ENTITY_TOO_LARGE-отказ обработки запроса из-за большого размера; О static int HTTP_EXPECT_FAILED - запрос ожидания не выполнен; Q stat ic int HTTP_FORBIDDEN - запрос принят, но выполнен не будет; Q static int HTTP_GATEWAY_TIMEOUT - сервер не получил своевременный ответ;
Справочник по Java 2 Micro Edition
2.4.4. Интерфейс Datagram Общий интерфейс дейтаграммы. Методы Q String g&tAddress () - получает адрес дейтограммы; Q byte [ ] getData ( ) - получает данные; О int getLength ( ) - получает продолжительность соединения; Q int getOff set () — получает смещение; Q void reset () - производит сброс или обнуление указателей для чтения и записи; Q void .setAddress (Datagram reference) - устанавливает адрес дейтограммы, взятый с другой выбранной дейтограммы; О void setAddress (String addr) - устанавливает адрес дейтограммы; Q void setData (byte [] b u f f e r , int o f f s e t , int len) -устанавливает в буфере смещение и длину; О void setLength(int len) - устанавливает длину.
2.4.5. Интерфейс DatagramConnection Определяет возможность связи дейтограммы. Методы Q int getMaximumLength ()—получает максимальную длину дейтограммы; Q int getNominalLength() -получает номинальную длину дейтограммы; Q Datagram newDatagram(byte [] b u f , int size) - создает новый объект дейтограммы с указанным размером буфера; О Datagram newDatagram(byte[] b u f , int size. String addr) создает новый объект дейтограммы с указанным размером буфера и адресом ввода-вывода; Q Datagram newDatagram(int size) - создает новый объект дейтограммы определенного размера; Q Datagram newDatagram(int s i z e , String addr) - создает новый объект дейтограммы определенного размера и с указанием адреса вводавывода; Q void receive (Datagram dgram) - принимает дейтограмму; О void send (Datagram dgram) - отсылает дейтограмму.
2.4.6. Интерфейс HttpConnection Декларирует Методы и Константы для протокола соединения HTTP. Методы *Q long getDate () -возвращает данные; Q String getFi le ( ) - возвращает часть файла по адресу URL; Q String getHeaderField(int n) - возвращает заголовок файла по индексу;
Пакет javax.microedition.io Q void write (int с) - записывает один единственный символ; Q void write (String str) - записывает строку текста; Q void w r i t e (String str, int o f f , int len) - совершаетзапись заданной части строки текста. Константа Q protected Object lock - используется при синхронизации определенных действий в потоке.
2.3.14. Исключения О EDFException - сигнализирует о конце файла; О interruptedlOException - сигнализирует о прерванном действии по вводу-выводу; О lOException - указывает на исключение ввода вывода; Q UnsupportedEncodingException - указывает на невозможность перекодировки; О UTFDataFormatException - сигнализирует о прочтении строки формата UTF-8.
2.4. Пакет javax.microedition.io Этот пакет обеспечивает мобильное устройство связью с сетью.
2.4.1. Интерфейс CommConnection Находит последовательный порт. Методы Q int getBaudRate О-получает скорость передачи данных в бодах для связи; О int setBaudRate (int baudrate) -устанавливает скорость передачи данных в бодах для связи. . \
2.4.2. Интерфейс Connection Общий тип всей связи с сетью. Метод О void close ()•- закрывает имеющуюся связь с сетью.
2.4.3. Интерфейс ContentConnection Определяет связь с потоком. Методы Q String getEncoding ( ) - определяет кодировку потока; Q long getLength()-возвращает продолжительность соединения; О String getType () - возвращает тип соединения.
Справочник по Java 2 Micro Edition void write (byte [] buf , int o f f , int len) - производит запись определенных байт указанных в параметре len из параметра b потока печати; Q void write (int b) — записывает байт в поток печати.
2.3.12. Класс Reader Абстрактный класс, предназначенный для чтения символьных потоков данных. Конструкторы Q protected Reader () - создает новый поток для чтения; Q protected Reader (Object lock) - создает новый поток для чтения, синхронизирующийся с параметром lock. Методы ' . О abstract void closet) - закрывает поток данных; О void mark (int readAheadLimit) - маркирует определенную позицию в потоке; О boolean markSupported ( ) - проверяет поддержку маркировки и сброса позиции в потоке; Q int read ( ) - производит чтение символа; Q int read ( c h a r t ] c b u f ) — производит чтение массива символов; Q abstract int r e a d ( c h a r t ] cbuf, int o f f , int len) -производит чтение в массив; Q boolean ready () - определяет готовность потока для чтения данных; О void r e s e t ( ) - сбрасывает позицию маркера; Q long skip (long n) - пропускает заданные символы. Константа Q protected Object lock - используется при синхронизации определенных действий в потоке. ,
2.3.13. Класс Writer Абстрактный класс, предназначенный для записи символьных данных в выходной поток. Конструкторы Q protected W r i t e r ( ) - создает новый символьный поток для записи данных; G protected Writer (Object lock) - создает новый символьный поток для записи данных, синхронизирующийся с параметром lock. Методы О abstract void c l o s e t ) - закрывает поток данных; О abstract void f l u s h O - сбрасывает поток данных; Q void write (chart] c b u f ) - производит запись в массив символов; О abstract void w r i t e ( c h a r t ] cbuf, int o f f , int len)-совершает запись заданной части массива символов;
Пакет java.io Q void write (char[] c b u f , int o f f , int len) - производит запись определенных символов указанных в параметре len из параметра b выходного потока; Q void write (int с) - записывает один символ; Q void write (String str, int o f f , int len) - производит запись определенной части строки текста указанной в параметре len из параметра b выходного потока;
2.3.11. Класс PrintStream Расширяет выходной поток способностью печати данных. Конструктор Q PrintStream (OutputStream out) - формирует объект класса PrintStream, отвечающий за создание нового потока печати. Методы Q boolean checkError ( ) - проверяет состояние потока; Q void close () - закрывает поток данных; Q void f l u s h ( ) -сбрасывает поток данных; Q void print (boolean b) - производит печать логического значения; Q void print (char с) - производит печать значения типа char; Q void print (char [ ] s) - производит печать массива символов; Р void print (int i) - производит печать значения типа int; О void print (long 1) - производит печать значения типа long; Q void print (Object obj ) - производит печать объекта; Q void print (String s) - производит печать строки текста; О void print In ( ) - производит печать, заканчивая переводом на новую строку; Q void println(booleaft x) —производит печать логического значения, заканчивая печать переводом на новую строку; Q void println(char x) - производит печать значения типа char, заканчивая печать переводом на новую строку; Q void println (char [] x) — производит печать массива символов, заканчивая печать переводом на новую строку; О void println (int x) — производит печать значения типа int, заканчивая печать переводом на новую строку; О void println (long x) — производит печать значения типа long, заканчивая печать переводом на новую строку; Q void println (Object x) - производит печать объекта, заканчивая печать переводом на новую строку; Q void println (String x) - производит печать строки текста, заканчивая печать переводом на новую строку; Q protected void setError() - приводит поток, содержащий некоторые ошибки к состоянию true;
Справочник по Java 2 Micro Edition InputStreamReaider (InputStream is, String enc) - создает объект класса InputStreamReader, используя кодировку, заданную в параметре епс. Методы Q void с lose () - Закрывает поток; Q void m a r k ( i n t readAheadLimit) - маркирует позицию в потоке; Q boolean markSupported() - определяет поддержку маркировки и сброса позиции в потоке; Q int read ( ) - производит чтение символа; Q int read ( c h a r [ ] c b u f , int o f f , int len) - производит чтение символа в массив; Q boolean ready () — определяет готовность потока на чтение данных из него; О void reset ( ) — сбрасывает позицию маркера; Q long skip (long n) - пропускает заданные символы.
2.3.9. Класс OutputStream Абстрактный класс, предназначенный для работы с выходным потоком байт. Конструктор Q OutputStream ( ) - Конструктор абстрактного класса OutputStream. Методы Q void close () - закрывае-т выходной поток; Q void f l u s h () - осуществляет сброс выходного потока; Q void write (byte [] b) - записывает массив байт в выходной поток; Q void w r i t e ( b y t e [ ] b, int o f f , int len) - производит запись определенных байт указанных в параметре len из параметра b выходного потока; Q abstract void write (int b) - записывает определенный байт в выходной поток.
2.3.10. Класс OutputStreamWriter Наследуется от класса Writer, реализуя Методы для записи символьных данных в выходной поток с перекодировкой. Конструкторы Q OutputStreamWriter (OutputStream os) - создает объект OutputStreamWriter, используя кодировку по умолчанию; Q OutputStreamWriter(OutputStream os , String enc) - создает объект'OutputStreamWriter, используя кодировку, заданную в параметре епс. Методы О void close () - закрывает поток данных; Q void f l u s h () - сбрасывает поток данных;
Пакет java.io
1
Q void writeByte (int v) - производит запись в выходной поток восемь младших бит; Q void writeChar (int v) - производит запись в выходной поток данHbix значение типа char (один символ - это два байта); О! void writeChars (String s) - производит запись в выходной поток данных строку текста; О void w r i t e l n t ( i n t v) - производит запись в выходной поток данных значения типа int (четыре байта); О void writeLong (long v) - производит запись в выходной поток данных значения типа long (восемь байт); Q void writeShort (int v) - производит запись в выходной поток данных значения типа short (два байта); О void writeUTP (String str) - записывает строку текста в выходной поток данных. Константа О protected OutputStream out - выходной поток данных.
2. 3. 7. Класс InputStream Абстрактный класс, предназначенный для работы с входным потоком байт. Конструктор О InputStream ( ) - Конструктор абстрактного класса InputStream. Методы Q int available ( ) - возвращает доступное количество байт для чтения из входного потока; О void c l o s e t ) - закрывает входной поток; Q void mark(int readlimit) - маркирует заданную позицию в входном потоке; Q boolean markSupp'orted ( ) - проверяют объекты на поддержку установки и сброса маркера; Q abstract read ( ) - производит чтение каждого последующего байта во входном потоке данных; Q int read (byte [] b) - производит чтение байт из массива во входном потоке данных; Q int read (byte [] b, int o f f , int len) - читает определенный байт, указанный в параметре len из параметра b входного потока данных; Q void resetO - сбрасывает позицию маркера; G long skip (long n) - пропускает заданные байты входного потока. -1
'
2. 3. 8. Класс InputStreamReader Наследуется от класса Reader, реализуя Методы для чтения символьных данных входного потока с перекодировкой. Конструкторы О InputStreamReader (InputStream is) - создает объект класса InputStreamReader, используя кодировку по умолчанию;
ЕШШНИНН!
Справочник по Java 2 Micro Edition
Q boolean readBoolean() - читает входной байт данных и если значение этого байта отлчно от 0, то возвращает true,- иначе возвращается значение false; Q byte readByteO - производит чтение и возврат одного входного байта; Q char readChar () - производит чтение и возврат одного входного символа; Q void readFully (byte [ ] b) - производит чтение входных байт, размещая их в массиве данных; D void readFully (byte [] b, int. o f f , int len) -производит чтение указанных входных байт параметра len из параметра Ь; Q int readlnt ( ) - производит чтение и возврат входных байт типа int (четыре байта); Q long readLongO - производит чтение и возврат входных байт типа long (восемь байт); Q short readShort () - производит чтение и возврат входных байт типа short (два байта); Q int readUnsignedShort ( ) - производит чтение и возврат двух входных байт в диапазоне от 0 до 256; Q String readUTF ( ) - читает строку текста в формате UTF-8; Q Static String readUTF (Datalnput in) - производит чтение из входного потока строки символов; Q void reset () - сбрасывает позицию маркера; Q long skip (long n) - пропускает заданные байты входного потока; Q int skipBytes (int n) - переходит по входному потоку, минуя пропущенные байты. Константа Q protected InputStream in - входной поток данных.
2.3.6. Класс DataOutputStream Этот класс наследуется от интерфейса DataOutput, реализуя при этом все его Методы. Конструктор О DataOutputStream(OutputStream out) - создает новый выходной поток данных. Методы Q void с lose () - закрывает выходной поток; Q void flushQ - производит сброс потока данных; Q void write (byte [] b, int o f f , int len) - производит запись определенных байт указанных в параметре len из параметра b выходного потока; Q void write (int b) - производит запись в выходной поток восемь младших бит; Q void writeBoolean (boolean v) - записывает логическую переменную в выходной поток данных;
Пакет java.io
2.3.4. Класс ByteArrayOutputStream Производит запись потока байт из памяти в массив выходных данных. Конструкторы Q ByteArrayOutputStream ( ) - создает новый выходной поток для записи в массив байт; Q By teArrayOutput Stream (int s i z e ) - создает новый выходной поток для записи в массив байт с заданным размером. \ Методы Q void c l o s e ( ) - закрывает выходной поток, попутно освобождая все захваченные ресурсы этим потоком; Q void reset () - сбрасывает в ноль счетчик выходных данных; Q int size () - возвращает текущий размер буфера данных; U byte[] toByteArray() - создает массив байт; Q String toStringO - производит преобразование содержимого буфера в строку текста; О void write (byte [] b, int o f f , int len) - записывает определенный байт, указанный в параметре len из параметра b в выходной поток; U void write ( i n t b) - записывает байт в выходной поток. Константы Q protected byte [] buf - заданный буфер данных; Q protected int count - количество байт в буфере. •
2.3.5. Класс DatalnputStream Этот класс наследуется от интерфейса Data Input, реализуя при эхом все его Методы. Конструктор Q DatalnputStream(InputStream in) - создает новый входной поток данных. Методы Q int available ( ) - возвращает доступное количество байт для чтения из входного потока; Q void c l o s e ( ) - закрывает входной поток; Q void mark (int readlimit) — маркирует заданную позицию во входном потоке; . О boolean markSupportedt) - проверяет объект класса DatalnputStream на поддержку установки и сброса маркера; Q int read ( ) - производит чтение каждого последующего байта во входном потоке данных; Q int read (byte [] b)-производит чтение байт из массива во входном потоке данных; Q int read (byte [] b, int o f f , int len) - читает определенный байт, указанный в параметре 1 en из параметра b входного потока данных;
Справочник по Java 2 Micro Edition Q void writelnt (int v) - производит запись в выходной поток данных -значения типа int (четыре байта); Q void writeLong( long v) - производит запись в выходной поток данных значения типа long (восемь байт); О void writeShort (int v) - производит запись в выходной поток данных значения типа short (два байта); Q void writeUTF (String str) - записывает строку текста в выходной поток данных.
2.3,3. Класс ByteArraylnputStream Совершает чтение входного потока байт из массива данных для дальнейшего размещения их в памяти. Конструкторы Q ByteArraylnputStream (byte [ ] b u f ) - создает объект класса ByteArraylnputStream, параметр buf будет содержать буфер данных; Q ByteArraylnputStream(byte[] buf, int offset, int length) — создает объект класса ByteArraylnputStream. Параметр buf будет содержать буфер данных, параметр o f f s e t задает смещение от первого байта, а параметр length определяет максимальное значения буфера. Методы Q int available () - возвращает количество байт входного потока дан1 ных; ' О void close () - закрывает входной поток, попутно освобождая все захваченные ресурсы этим потоком; О void mark (.int readAheadLimit) - устанавливает маркер в заданной позиции потока данных; Q boolean markSupported() - проверяют объект класса ByteArraylnputStream на поддержку установки и сброса маркера; Q int read ( ) - производит чтение каждого последующего байта во входном потоке данных; Q int read (byte [] b, int o f f , int len) - читает определенный байт, указанный в параметре len из параметра b входного потока данных; Q void reset () - сбрасывает значение к установленному маркеру; Q long skip (long n) - пропускает заданные байты входного потока. Константы Q protected Q protected тока; Q protected Q protected тока.
byte[] buf - массив байт; int count - последний индекс для чтения из входного поint mark - позиция или маркер во входном потоке данных; int pos - последующий индекс для чтения из входного по-
Пакет java.io
2.3.1. Интерфейс Data Input
•• -
Декларирует Методы для чтения простых типов во входном потоке данных. Методы О boolean readBoolean ( ) — читает входной байт данных и если значение этого байта отлчно от 0, то возвращает true, иначе возвращается значение false; Q byte readByteO - производит чтение и возврат одного входного байта; О char readChar ( ) - производит чтение и возврат одного входного символа; G void. readFully (byte [] b) - производит чтение входных байт, размещая их в массиве данных; Q void readFully (byte [] b, int o f f , int len) -производит чтение указанных входных байт параметра len из параметра Ь; Q Int readlnt ( ) - производит чтение и возврат входных байт типа int (четыре байта); Q long readLong ( ) — производит чтение и возврат входных байт типа long (восемь байт); Q short readshort ( ) — производит чтение и возврат входных байт типа short (два байта); О int readUnsignedByte ( ) - производит чтение и возврат одного входного байта в диапазоне от 0 до 256; О int readUnsignedShort ()-производит чтение и возврат двух, входных байт в диапазоне от 0 до 256; Q String readUTF ()-читает строку текста в формате UTF-8; Q int skipBytes (int n) - переходит по входному потоку, минуя пропущенные байты.
2.3.2. Интерфейс DataOutput Декларирует Методы для записи простых типов в выходной поток данных. Методы Q void write (byte [] b) -записываете выходной поток массив байт; О void write (byte [] b, int o f f , int len) - производит запись определенных байт указанных в параметр 1 en из параметра b выходного потока; О void write (int b) - производит запись в выходной поток восемь младших бит; G void writeBoolean (boolean v).-записывает логическую переменную в выходной поток данных; О void writeByte (int v) - производит запись в выходной поток восемь младших бит; ED void writeChar (int v) - производит запись в выходной поток данных значения типа char (один символ - это два байта); Q void writeChars (String s) - производит запись в выходной поток данных строки текста;
Справочник по Java 2 Micro Edition О Enumeration elements () - возвращает число имеющихся элементов в' массиве данных; О void ensureCapacity (int minCapacity) — увеличивает вместимость массива данных; Q Object f irstElement ( ) - возвращает самый-первый элемент всего массива; О int indexOf (Object elem) - проверяет массив на присутствие объекта; Q int indexOf (.Object elem, int index) - проверяет массив на присутствие объекта по его индексу в массиве данных; .Q void insertElementAt (Object obj , int index) — вставляет объект в массив по заданному индексу; Q boolean isEmpty()-проверяет массив, не пустой ли он; Q Object lastElement ( ) - возвращает самый последний элемент всего массива данных; Q int lastlndexOf (Object elem) -возвращает последний индекс данного элемента в массиве; Q int lastlndexOf (Object elem, int index) - проверяет последнее присутствие объекта в массиве по его индексу; Q void removeAllElements ( ) - удаляет все элементы массива; Q boolean removeElement (Object obj ).-удаляет элемент массива; О void , removeElement At (int index) - удаляет элемент массива по индексу; Q void setElementAt (Object obj , int index), -устанавливаетэлемент в массив по индексу; Q void setSize(int newSize) - задает размер массива; Q int size () - определяет размер массива; G String toStringO - возвращает строковое представление массива данных; G void trimToSize() - уменьшает размерность массива. Константы Q protected int capacitylncrement - автоматическое увеличение массива на заданное число элементов, то есть шаг увеличения массива; Q protected int elementCount — заданное число элементов массива; G protected Obj ect [ ] elementData - массив данных, в котором сохранены элементы массива.
2.2.11. Исключения Р EmptyStackException - указывает на пустой стек; Q NoSuchElementException - указывает на отсутствие элементов в определенном перечислении.
2.3. Пакет Java.io Классы этого пакета отвечают за работу с входными и выходными потоками данных.
Пакет java.util
ШИВНШЕШ!
Методы О boolean cancel () - отменяет выполнение задачи; Q abstract void run ( ) - определяет действие для выполнения планировщиком задач; Q long scheduledExecutionTime() - возвращает время выполнения задачи.
2.2.9. Класс TimeZone Устанавливает и определяет часовой пояс. Конструктор О TimeZone ( ) - создает объект класса TimeZone. Методы Q static S t r i n g E ] getAvailablelDs (} - получает доступные идентификаторы часового пояса; О s t a t i c TimeZone getDefault ()-получает часовой пояс региона; D String getlDO - получает идентификатор часового пояса; О abstract int getRawOf f set ( ) - получает время по Гринвичу для часового пояса местонахождения; Q static TimeZone getTimeZonef String ID) - получает часовой пояс; Q abstract boolean useDaylightTime ()-необходим для определения использования часовым поясом перехода на летнее время.
2.2.10. Класс Vector Создает массивы любого размера. Имеет возможность изменять размер заданного массива. Конструкторы Q Vector ( } - создает пустой массив для содержания объектов; Q Vector (int initialCapacity) - создает массив объектов с указанной размерностью; Q V e c t o r ( i n t initialCapacity, int.capacitylncrement)-создает массив объектов с указанной размерностью и заданным размером дополнений к этому массиву; Методы > Q void addElement (Object obj ) - добавляет к массиву объектов еще один объект; Q int capacity () - узнает текущую вместимость заданного массива объектов; Q boolean contains (Object elem) - определяет наличие указанного элемента в массиве объектов; Q void copylnto (Object [ ] anArray) - копирует заданные элементы в массив объектов; Q Object elementAt (int index) - возвращает искомый компонент по указанному индексу;
Справочник по Java 2 Micro Edition
2.2.6. Класс Stack Реализует функциональность стека. Конструктор Q Stack () - создает пустой стек. Методы Q boolean empty () - проверяет пустой созданный стек или нет; . Q Object peek () - просмотр стека; Q Ob j ect pop ( ) - удаляет последний объект из стека; Q Object push (Object item) - помещает объект в стек; Q int search (Object о)•-возвращает начальную позицию для первого объекта в стеке.
2.2.7. Класс Timer Реализует возможность работы со временем по принципу таймера. Конструктор О Timer () - создает таймер. Методы Q void cancel () — закрывает работу таймера; Q void schedule (TimerTask task, Date time) - назначает задачу на заданное время; Q void •schedule(TimerTask task, Date f i r s t T i m e , long period) - назначает задачу на заданное время, с ее последующим повторным выполнением. Частота повторений задается фиксированными промежутками времени; Q void schedule (TimerTask task, long delay) - назначает выполнение задачи по прошествии заданного промежутка времени; Q void schedule(TimerTask task, long delay, long period) — назначает выполнение задачи по прошествии заданного промежутка времени, с ее последующим повторным выполнением. Частота повторений задается фиксированными промежутками .времени; Q void scheduleAtFixedRate(TimerTask task, Date f i r s t T i m e , long period) — назначает задачу на заданное время с ее последующим повторным выполнением. Частота повторений назначается относительно абсолютного времени; Q void scheduleAtFixedRate(TimerTask task, long delay, 'long period) - назначает выполнение задачи по прошествии заданного промежутка времени с ее последующим повторным выполнением. Частота повторений назначается относительно абсолютного времени.
2.2.5. Класс TimerTask Планировщик задач. ; Конструктор Q protected TimerTask () - создает новую задачу.
Пакет java.util Конструкторы Q HashtableO - создает пустой объект класса Hashtable; Q Hashtable (int i n i t i a l C a p a c i t y ) - создает объект класса Hashtable с заданной вместимостью. Методы О void clear () -очищает объект класса Hashtable-от набора имеющихся ключей; Q boolean contains (Object value) - определяет наличие различных ключей; О boolean containsKey (Object key) - определяет наличие определенного ключа; Q Enumeration elements () — возвращает последовательность имеющихся элементов; О Object get (Object key) - получает необходимый объект^ используя при этом заданный для этого объекта ключ; U boolean isEmpty() - проверяет объект класса Hashtable на наличие ключей; Q Enumeration keys О - возвращает последовательность доступных ключей; О Object put(0bject key, Object value) - сохраняет объект и заданный для этого объекта ключ; Q protected void rehash () - увеличивает вместимость объекта класса Hashtable; Q Object remove (Object key) - удаляет указанный ключ; О int size () - определяет количество имеющихся ключей; Q String toStringO - возвращает строковое представление объекта класса Hashtable.
2.2.5. Класс Random Генератор случайных чисел. Конструкторы ', Q Random ( ) - создает генератор случайных чисел; Q Random (long seed) - создает объект класса Random, сгенерировав целое длинное число. Методы Q protected int next (int bits) - генерирует следующее случайное число; О int nextInt ( ) - генерирует целое случайное число из заданной последовательности; О long nextLong ( ) - генерирует целое длинное случайное число из заданной последовательности; Q void setSeeddong seed) - устанавливает заданное начальное число для последующей генерации случайных чисел.
Справочник по Java 2 Micro Edition Q Q О Q Q Q Q О О Q Q Q Q Q Q О Q О О Q И Q •Q Q О
static int DECEMBER - значение, указывающее месяц года Декабрь; static int FEBRUARY - значение, указывающее месяц года Февраль; static int FRIDAY - значение, указывающее день недели пятницу; static int HOUR - значение, указывающее время; static int HOUR_OF_DAY - значение, указывающее время и день недели; static int JANUARY - значение, указывающее месяц года Январь; static int JULY - значение, указывающее месяц года Июль; static int JUNE - значение, указывающее месяц года Июнь; static int MARCH - значение, указывающее месяц года Март; static int MAY - значение, указывающее месяц года Май; static int MILLISECOND - формат записи временив миллисекундах; static int MINUTE - формат записи времени в минутах; s t a t i c int MONDAY - значение, указывающее день недели пятницу; static int MONTH - месяц; static int NOVEMBER - значение, указывающее месяц года Ноябрь; static int OCTOBER - значение, указывающее месяц года Октябрь; static int PM - формат, отображающий запись времени после полудня; static int SATURDAY - значение, указывающее день недели суббота; static int SECOND - устанавливает отображение времени в секундах; static int SEPTEMBER-значение, указывающее месяц года Сентябрь; static int SUNDAY - значение, указывающее день недели воскресенье; static int THURSDAY - значение, указывающее день недели четверг; static int TUESDAY - значение, указывающее день недели вторник; static int WEDNESDAY - значение, указывающее день недели среда; static int YEAR - значение, указывающее год.
2.2.3. Класс Date Реализует возможность работы с датой. Конструкторы Q Date ( ) - создает объект класса Date; О Date (long date) - создает объект класса Date с форматом записи 00:00:00. Методы О boolean equals (Object ohj ) - сравнивает две даты; О long getTime ( ) - получает время в миллисекундах; Q int hashCode ( ) - возвращает специальный код (хеш-код) объекта класса Date; Q void setTimedong time) - устанавливает время.
2.2.4. Класс Hashtable Предоставляет возможность хранения объектов с доступом к ним по определенно заданному ключу.
Пакет java.util Q Object nextElement { ) - возвращает последующий элемент перечисления в том случае, если перечисления содержат более одного элемента.
2.2.2. Класс Calendar Необходим для работы с датой и временем, выполняет функции обыкновенного календаря. Конструктор О protected Calendar () - создает календарь. Язык и часовой пояс задаются по умолчанию. Методы О boolean after (Object when) - сравнивает два объекта и возвращает значение true в том случае, если время представленное объектом when, находится после времени представленного другим сравниваемым объектом;. G boolean before (Object when) - сравнивает два объекта и возвращает значение true в том случае, если время представленное объектом when, находится до времени представленного другим сравниваемым объектом; Q boolean equals (Object obj ) - сравнивает объекты; Q . i n t get (int f i e l d ) - получает значение определенного поля, например, время, день, месяц, год; Q static Calendar getlnstance ( ) - получает параметры часового пояса и языка по умолчанию; Q static Calendar getlnstance (TimeZone zone) - получает параметры часового пояса и языка данного региона; О Date getTime ( ) - получает время; О protected long getTimelnMillis ( ) — получает время по Гринвичу, производя запись в виде миллисекунд; Q TimeZone getTimeZone ( ) - определяет часовой пояс региона; Q void s e t ( i n t f i e l d , int v a l u e ) - задает определенному полю значение времени; Q void setTime (Date date) - устанавливает необходимую дату; Q protected void setTimelnMillis (long m i l l i s ) -устанавливает время по Гринвичу, производя запись в виде миллисекунд; Q void setTimeZone (TimeZone value) — устанавливает часовой пояс региона. Константы Q static int AM - формат, отражающий запись времени до полудня; Q static int AM_PM - формат, отражающий запись времени до полудня и после полудня; Q static int APRIL - значение, указывающее месяц года Апрель; Q s t a t i c int AUGUST -значение, указывающее месяц года Август; Q static int DATE - значение, указывающее день; О static int DAY_OF_MONTH - значение, указывающее день и месяц; Q s t a t i c int DAY_OF_WEEK - значение, указывающее день недели;
Справочник по Java 2 Micro Edition
2.1.17. Исключения Q Exceptions - исключения для классов и подклассов; Q ArithmeticException - арифметическое исключение; О ArrayIndexOutOf BoundsException - исключение обрабатывающее неправильный индекс в массив'е данных; L3 ArrayStoreException - исключение обрабатывающее неправильно заданный тип объекта в массиве объектов; О ClassCastException - неправильно указан подкласс объекта; Q ClassNotFoundException - класс не найден; Q IllegalAccessException - нет доступа к классу; Q 111 ega I Argument Exc ept ion- указан неправильный аргумент; Q IllegalMonitorStateException - мониторинг объектов; О IllegalStateException - неправильно вызванный метод; Q IllegalThreadStateException - неправильные установки потока; Q IndexOutOf BoundsException - исключает неверный указанный индекс; Q InstantiationException - исключает ситуацию в создании или вызове членов абстрактного класса; О InterruptedException - исключает прерывание потока находящегося в состоянии ожидания: О NegativeArraySizeException - исключает ситуацию в создании большего размера массива данных, чем было указано при инициализации; Q NumberFormatException - неправильное преобразование строки в целочисленный тип данных; О RuntimeException.- суперкласс исключений времени исполнения виртуальной машины Java; О Secur ityExcept ion - менеджер безопасности; Q StringlndexOutOf BoundsException - выход индекса за приделы строки.
2.1.18. Ошибки Q Error - обобщенная модель ошибок; Q OutOf Memory-Error - ошибки связанные с выходом за пределы памяти; Q VirtualMachineError - ошибки времени щрполнения.
2.2. Пакет java.util В этом пакете содержатся классы стандартных утилит для создания Java 2 ME приложений. Пакет сильно урезан по сравнению со стандартным пакетом Java 2 SE.
2.2.1. Интерфейс Enumeration Декларирует возможность доступа к элементам. Методы Q boolean hasMoreElements ( ) - проверяет соответствующие перечисления на наличие элементов;
Пакет Java.long
2.1.15. Класс Thread Создает поток в работе приложения для виртуальной Java машины, мобильных телефонов. Доступна многопоточность. Конструкторы О Thread ( ) - создает новый поток; Q Thread(Runnable target) - создает новый поток с заданным объектом в параметре target, реализующем возможности интерфейса Runnable. Методы Q static int act iveCount ( ) - возвращает количество задействованных потоков; Q static Thread currentThread() - возвращает выполняющийся в данный момент поток; Q int getPriority ( ) - узнает приоритет определенного потока; О boolean isAliveO - тестирует поток на работоспособность; Q void join О - ожидает окончание потока; Q void setPriority (int 'newPriority) - устанавливает приоритет для потока; Q static void sleep (long m i l l i s ) - останавливает выполнение потока, на заданное количество времени, измеряемое в миллисекундах; Q void start ( ) -дает команду на выполнение потока посредством метода run () интерфейса Runnable; Gl String toSt ring ()-возвращает строковое представление потока; G static void yield () - регулирует вызовы последующих потоков низших по приоритету. Константы О static int MAX_PRIORITY - максимальный приоритет потока; Q static int MIN_PRIORITY — минимальный приоритет потока; Q static int NORM_PRIORITY - приоритет по умолчанию.
2.1.16. Класс Throwable \
Суперкласс для всех классов, предназначенных для работы с ошибками и исключениями в языке программирования Java. Конструкторы Q Throwable () - создает новый объект класса Throwable; Q Throwable (String message) - создает новый объект класса Throwable с заданным сообщением об ошибках. Методы Q String getMessageO - возвращает сообщение об ошибке; Q void printStackTrace ( ) - отслеживает ошибки на выходном потоке; Q String toStringO - возвращает описание объекта класса Throwable.
Справочник по Java 2 Micro Edition Q void getCh'ars (int srcBegin, int srcEnd, char[] dst, int dstBegiri) - копирует в символьный массив содержимое строкового буфера; О S t r i n g B u f f e r . i n s e r t ( i n t o f f s e t , boolean b ) - вставляет в буфер строковое представление логической переменной из параметра boolean b; Q StringBuf fer insert (int o f f s e t , ch'ar с ) - вставляет в буфер символ из параметра с; Q StringBuffer insert(int o f f s e t , char[] str) - вставляет в буфер массив символов из параметра char [ ] str; Q StringBuffer insert (int o f f s e t , int i) - вставляет в буфер строковое представление переменной типа int; О StringBuffer insert(int o f f s e t , long 1)-вставляет в буфер строковое представление переменной типа long; Q StringBuffer insert(int o f f s e t , Object o b j ) - вставляет в буфер строковое представление объекта; Q StringBuffer insert(int o f f s e t . String str) - вставляет в буфер строку текста; Q int lengthQ - определяет длину строки; О StringBuffer reverse () - производит замену буфера новой символьной последовательностью; Q void setCharAt (int index, char ch) - устанавливает символ в буфер по заданному индексу; О void setLength(int newLength) - устанавливает новую длину для буфера; Q String toString() - преобразует содержимое буфера в строку.
2.1.14. Класс System Содержит ряд системных методов.
Методы Q static void arraycopy(Object src, int src oosition. Object dst, int dst_position, int length) - копирует массив из указанного массива по заданной позиции; О static long currentTimeMillis ( ) - возвращает время, измеряемое в миллисекундах; Q static void exit (int status) - производит выход из программы; Q static void gc ( ) - совершает сборку мусора; Q static String getProperty (String key) - возвращает приоритетное свойство по строковому ключу; О static int identityHashCode (Object x)-возвращает специальг ный код (хеш-код) объекта. Константы О static PrintStream err - выходной поток, сообщающий об имеющихся ошибках; D static PrintStream out - выходной поток данных.
Пакет Java.long Q s t a t i c String valueOf (int i) - возвращает строковое представление переменной типа int; Q static String valueOfdong 1)"- возвращает строковое представление переменной типа long; Q static String valueOf (Object obj } - возвращает строковое представление объекта.
2.1.13. Класс StringBuffer Класс S t r i n g B u f f e r может содержать строки символов любого размера.
Конструкторы Q S t r i n g B u f f e r O - создает, пустой объект класса S t r i ngBu f f e r, то есть объект не имеет определенной символьной последовательности, с длинной не более шестнадцати символов; Q StringBuffer (int length) - создает объект класса StringBuffer с заданной длинной; О StringBuffer (.String str) - создает объект класса StringBuffer со значением из параметра str, являющегося объектом класса^ t r ing. Методы Q StringBuffer append (boolean b) - добавляет в конец буфера логическую переменную в строковом представлении; • Q StringBuffer append (char с) - добавляет в конец буфера символ; Q StringBuffer append (char [ ] str) - добавляет в конец буфера массив символов; Q StringBuffer append(char[] str, int o f f s e t , int len) добавляет в конец буфера массив символов по начальному индексу и длине массива символов; G StringBuffer append (int i) - добавляет в конец буфера значение типа int в строковом представлении; ID StringBuffer append (long 1) - добавляет в конец буфера значение типа long в строковом представлении; Q StringBuffer append (Object obj) - добавляет в конец буфера объект в строковом представлении; Q StringBuffer append(String str) - добавляет в конец буфера строку текста; Q int capacityQ - возвращает имеющеюся свободную емкость буфера; О char c h a r A t ( i n t index) - возвращает символ по заданному индексу в переменной index; Q StringBuffer delete (int start, int end) - удаляет подстроку из строки по указанному начальному значению в параметре start и конечному в параметре end; О StringBuffer deleteCharAt (int index) - удаляет символ из строки по указанному индексу в параметре index; Q void ensureCapacity (int minimumCapacity) - задает минимальную емкость буфера;
Справочник по Java 2 Micro Edition int indexOf {int ch, int fromlndex) — возвращает положение первого символа в строке текста и производит поиск по заданному индексу в параметре fromlndex; Q int indexOf (String str)-возвращает положение первого символа в подстроке текста; Q int indexOf (String str , int fromlndex) — возвращает положение первого символа в подстроке текста и производит поиск по заданному индексу'в параметре fromlndex; О int lastlndexOf (irjt ch) — возвращает положение последнего символа в подстроке текста; О int lastlndexOf (int ch, int fromlndex) — возвращает,положение последнего символа в подстроке текста и производит поиск по заданному индексу в параметре fromlndex; Q int length () -возвращает длину определенной строки текста; О boolean regionMatches(boolean ignoreCase, int t o f f s e t , String other, int • oof f set, int 1 e n ) - проверяет заданную область те.кста на совпадение; Q String replace(char oldChar, char newChar) - производит замену строки текста на новую строку из параметра oldChar в параметр newChar;. Q boolean s t a r t s W i t h ( String p r e f i x ) - проверяет строку на совпадение с начальным указанием префикса; Q boolean s t a r t s W i t h ( S t r i n g p r e f i x , int t o f f s e t ) -проверяет строку на совпадение с начальным указанием префикса и индекса; Q String substring (int beginlndex) - возвращает новую строку текста, являющуюся подстрокой этого текста; Q String substring(int beginlndex, int endlndex) -возвращает новую строку текста, являющуюся подстрокой этого текста заданной начальным и конечным индексами; Q char [ ] ^toCharArray ( ) — конвертирует строку текста в массив символов; О String toLowerCase() - приводит строку текста к строчному написанию; Q String t o S t r i n g ( ) - возвращает строковый объект; Q String toUpperCase ( ) - приводит строку текста к заглавному написанию; Q String trim ( ) - удаляет имеющиеся пробелы в начале и конце строки; Q static String valueOf (boolean b) - возвращает строковое представление логической переменной; Q static String valueOf(char с) - возвращает строковое представление переменной типа char; Q static String valueOf (char [ ] . . data) - возвращает строковое представление массива значений типа char; Q static String v a l u e O f ( c h a r [ ] data, int o f f s e t , int count) - возвращает строковое представление массива значений типа char с определенного начала по заданной длине;
'
Пакет Java.long Q String (byte [] bytes) - создает объект класса String из указанного массива байт в соответствующей кодировке поддерживаемой системой; Q String(byte[] bytes, int o f f , int len) - создает объект класса String из указанного массива байт в соответствующей кодировке поддерживаемой системой. Параметр o f f - это индекс первого байта, от которого происходит конвертация, и параметр len указывает на количество байт для конвертации; Q String (byte [] bytes, int o f f , int len, String enc) -создает объект класса String из указанного массива байт в соответствующей кодировке поддерживаемой системой. Параметр o f f - это индекс первого байта, от которого происходит конвертация, параметр len указывает на количество байт для конвертации и параметр епс на вид кодировки; Q String (by te [] bytes, String enc) -создает объект класса String из массива байт в заданной кодировке указанной в параметре епс; О String (char [] value) - создает строку текста из массива символов; Q String : (char [] value, int o f f s e t , int c o u n t ) - создает строку текста из массива символов. Параметр o f f s e t -.это начало массива и параметр count - длинна массива; Q String (String value) - создает объект класса String со значением определенным в параметре value; Q String (StringBuf fer b u f f e r ) - создает объект класса String со значением из параметра buffer, являющегося объектом класса StringBuffer. Методы Q char char At (int index) - возвращает символ по заданному индексу в параметре index, отсчет идет от значения 0; Q int compareTo (String anotherString) - сравнивает две строки на основании лексографии; Q String concat (String str) - конкатенация двух строк; Q boolean endsWith( String suffix)-—тестирует строку на окончание подстроки s u f f i x ; Q boolean equals (Object anObject) - сравнивает строки; Q byte [ ] getBy tes ( ) - конвертирует строку текста в массив байт в кодировке по умолчанию заданной системой устройства; D byte[] getBytes (String enc) - конвертирует строку текста в массив байт в кодировке указанной в параметре епс; Q void getCharstint srcBegin, int srcEnd, char[] dst, int dstBegin) - производит копирование'символов строки в массив символов; О int hashCode ( ) - возвращает специальный код (хеш-код) для строки текста; Q int indexOf (int ch) - возвращает положение первого символа в строке текста;
Справочник по Java 2 Micro Edition Q void wait (long timeout, int nanos) - приостанавливает работу потока на время заданное в миллисекундах, учитывая также дополнительное время заданное в наносекундах.
2.1.10. Класс Runtime
••' , i
Класс времени исполнения приложения. Методы Q void exit (int s t a t u s ) - осуществляет выход из работающего приложения; Q long f reeMemory ( ) - возвращает количество доступной памяти в мобильном устройстве; О void gc { ) - производит сборку мусора; Q s t a t i c Runtime getRuntime ()-возвращает объект времени исполнения во время работы программы; О long totalMemory ( ) - возвращает доступный объем памяти для виртуальной Java машины.
2.1.11. Класс Short Объектно-ориентированный класс-оболочка для простого типа Short. Конструктор О Short (short value) - создает объект класса Short. Методы u boolean equals (Object obj ) - сравнивает объекты; Q int hashcode ( ) - возвращает специальный код (хеш-код) объекта класса Short; Q static short parseShort (String s) - извлекает короткое целое десятичное число из заданного объекта класса String; Q static short parseShort (String s, int radix) -извлекает короткое целое десятичное число с использованием основания системы - исчисления из заданного объекта класса String; О short shortValue ()-возвращает значение переменной; О! String toString ( ) - возвращает объект класса String представляющий короткое целое значение. Константы О s t a t i c short MAX_VALUE - максимальное значение; Q static short MIN_VALUE - минимальное значение.
2.1.12. Класс String Создает символьные строки текста. Конструкторы О String ( ) - создает пустой объект класса String, то есть объект не имеет определенной символьной последовательности;
Пакет Java.long О s t a t i c long parseLong(String s, int radix) - извлекает большое целое десятичное число со знаком с использованием основания системы исчисления из заданного объекта класса String; О String toString ( ) - возвращает объект класса String представленный значением большого целого числа; Q. s t a t i c String toStringdong i)-возвращает заданный объект класса String как целое большое число; Q static String toStringdong i, int radix) -создаетстроковое представление большого целого числа на основании системы исчисления. Константы Q static long MAX_VALUE - максимальное значение; i G static long MIN_VALUE - минимальное значение.
2.1.8. Класс Math Математический класс, содержащий несколько методов для различных математических операций. Очень сильно урезан в отличие от класса Math из Java 2 SE. Методы Q static int abs(int a) - возвращает абсолютное значение из параметра int а заданное целочисленным значением; ,Q static long abs(long a) - возвращает абсолютное значение из параметра long а заданное большим целочисленным значением; Q static int max ( i n t a, int b ) - возвращает одно большее из двух значений типа int; Q static long max (long a, long b ) - возвращает одно большее из двух значений типа long; Q static int min(int a, int b) - возвращает одно меньшее из двух значений типа int; • О static long mindong a, long b) — возвращает одно меньшее из двух значений типа long.
2.1.9. Класс Object Суперкласс для всех классов Java. Все классы наследуются от класса Ob j ect и являются его подклассами Методы Q boolean equals (Object obj ) - сравнивает объекты; Q Class getClass ( ) - возвращает класс объекта; Q int hashCode ( ) - возвращает специальный код (хеш-код) для объекта; Q void n o t i f y () - пробуждает отдельно взятый поток; Q void n o t i f y A l l ( ) - пробуждает все имеющиеся потоки; Q String toString ( ) - возвращает строковое представление данного объекта; Q void wait () - приостанавливает работу потока; О void wait (long timeout) - приостанавливает работу потока на время заданное в миллисекундах;
Справочник по Java 2 Micro Edition int intValue ( ) - возвращает значение числа как тип int; long longValueO - возвращает значение числа как тип long; static int parselnt (String s) - извлекает целое десятичное число из заданного объекта класса String; Q static int parselnt (String s, int radix) - извлекает целое десятичное число со знаком с использованием основания системы исчис• ления из заданного объекта класса String; Q short s h o r t V a l u e ( ) - возвращает значение числа как тип short; О static String toBinaryString(int i) - создает строковое представление целочисленного значения в виде целого числа без знака в двоичном представлении; Q static String toHexString (int i) - создает строковое представление целочисленного значения в виде целого числа без знака в шестнадцатеричном представлении; Q static String toOctalString (int i) - создает строковое представление целочисленного значения в виде целого числа без знака в восьмеричном представлении; О String toString ( ) - возвращает объект класса String, представленный значением целого числа; О static String toString (int i) - возвращает заданный объект класса string как целое число; Q static String toStri'ng(int i, int radix) — создает строковое представление целого числа на основании системы исчисления; Q static Integer valueOf (String s) - возвращает новый объект класса Integer, инициализированный значением s; О static Integer valueOf (String s, int radix) -возвращает новый объект класса Integer, инициализированный значением s на основе системы исчисления. Константы D static int MAX_VALUE - максимальное значение; G static int MIN_VALUE - минимальное значение.
2.1.7. Класс Long Объектно-ориентированный класс-оболочка для простого типа long. Конструктор Q Long (long value) - создает объект класса Long. Методы Q boolean equals (Object obj ) - сравнивает объекты; Q int hashCode ( ) - возвращает специальный код (хеш-код) объекта класса Long; Q long longValueO - возвращает значение числа как тип long; Q static long parseLong( String s) - извлекает большое целое десятичное число из заданного объекта класса String;
Пакет Java.long Q s t a t i c char toLowerCase (char ch) - переводит символ в нижний регистр; О String toStringO - возвращает объект класса String, представленный значением Character; О static char toUpperCase (char ch) - переводит символ в верхний регистр. i Константы 0 static int MAX_RADIX - максимально доступное преобразование; U static char MAX_VALUE - максимальное значение; 01 static int MIN_RADIX - минимально доступное преобразование; Q static char MIN_VALUE - минимальное значение.
2.1.5. Класс Class Виртуальная Java машина создает объекты этого класса, которые представляют интерфейсы и классы языка Java. Методы Q static Class forName (String className) - возвращает объект Class,по названию класса; Q String getName ( ) - возвращает имя интерфейса, класса, массива классов, простых типов представляемых классом Class; Q InputStream getResourceAsStream(String name) - берет искомый ресурс с заданным именем; О boolean isArray ( ) — определяет, является ли объект массивом классов; Q boolean isAssignableFrom(Class els) - определяет, является ли интерфейс или класс суперинтерфейсом или суперклассом; Q boolean islnstance (Object obj )-определяет совместимость указанных объектов; О boolean islnterf асе ( ) - определяет, каким типом интерфейса представлен данный класс; , - Q Object newlnstance ( ) - создает новый экземпляр класса; Q String toString()- конвертирует объект к виду String.
2.1.6. Класс Integer Объектно-ориентированный класс для простого типа int. Конструктор ^ О Integer ( i n t value) - создает объект кЬасса Integer. Методы Q byte byteValue ( ) - возвращает значение в байтах; О boolean equals (Object obj) - сравнивает объекты; Q int hashCode ( ) - возвращает специальный код (хеш-код) объекта класса Integer;
Автор книги - Горнаков Станислав - занимается профессиональным
программированием
на
протяжении десятка лет. Им было создано большое количество программ и игр для компьютерных систем и мобильных телефонов. Он также является автором книги «DirectX 9. Уроки программирования на C++». Написать автору можно по адресу электронной почты: [email protected].
Программирование мобильных
телефонов на Java 2 ME
В этой книге описана платформа Java 2 Micro Edition, являющаяся стандартом в программировании приложений для мобильных телефонов. В ней подробно и доступно объясняется архитектура Java 2 ME, рассматриваются две имеющиеся на данный момент версии профилей MIDP 1.0 и MIDP 2.0, а также разбирается большое количество классов пользовательского интерфейса. В контексте этой книги изучаются основы построения мобильных программ, использование графики, техника создания игр для телефонов, работа со звуком. Книга будет интересна как начинающим программистам, так и более опытным, но не знакомым с платформой Java 2 ME.
Горнаков С. Г. УРОВЕНЬ ПОЛЬЗОВАТЕЛЯ /начинающий /средний опытный профессиональный
Компакт-диск содержит исходные коды и программы из книги, а также представлены две бесплатные среды программирования приложений для мобильных телефонов: Sun ONE Studio 4 Mobile Edition и J2ME Wireless Toolkit 2.1 компании Sun Microsystems и инструментальные средства от Nokia, Siemens, Sony Ericsson, Motorola, Samsung. Internet-магазин www.abook.ru e-mail: [email protected]
ISBN 5-94074-279-3
Web-сайт издательства www.dmkpress.ru Книга - почтой Россия. 103001. Москва, а/я 82 тел.: (095) 258-9194, 258-9195
9 "785940||742791|
Категория: Программирование/Программирование для мобильных устройств