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

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

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

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

Earlier in this chapter we described theprocess a MIDlet goes through from initialization to being destroyed. Youmay remember we talked about the relationship between the applicationsoftware manager and the MIDlet itself. The AMS provides the classwhich initializes the MIDlet class. When it is ready to do so, a call ismade to the startApp() method (every MIDlet has one).It must be remembered that the startApp() method can be calledmore than once during the lifecycle of the MIDlet.

The developer has,therefore, to be careful what code is put in this method. If, for example,the application were paused during execution, it would be unwise to48GETTING STARTEDdisplay the wrong screen to the user. It would cause confusion and it isbetter to let the user know what is happening. It would also be unwise toput all initialization for a recordstore into the MIDlet constructor becausethe data does not have to be re-initialized when the MIDlet is re-executedafter being released during the pauseApp() process.

A balance has tobe struck at this point to create a well-structured application.Why not just set the current display, say a Canvas object, directlyin the setCurrent() method in startApp()? More flexibility canbe given to the application if we set a global displayable object atthis point. It means that when the application is paused, whether by theAMS or the user, the global displayable object is set, for example to apause screen which is more informative. After setting the displayableand therefore the current display to this temporary ”paused” screen, thedisplayable object can then be set to the screen you wish the user tosee once execution resumes.

Therefore when startApp() is called andthe MIDlet resumes execution, the user will return to the place wherethey were when they paused.While we have been concerning ourselves with displaying the correctscreen to the user, we also have to remember that the MyGameCanvasobject is Runnable. During the startApp() process we have made acall to start the MyGameCanvas thread running. This enables the threadthat provides the animation for that class. While the application is in thepaused state, this resource should be released.

Although the applicationcan pause execution, it must be remembered that the device, through theAMS, may require the MIDlet to pause and release resources to deal withmore important issues, such as receiving a phone call or text message.import javax.microedition.lcdui.*;import javax.microedition.midlet.*;import java.io.IOException;public class Helloworld extends MIDlet implements CommandListener {private MyGameCanvas gameCanvas;private MyPauseCanvas pauseCanvas;private Command exit;private Command pause;private Command resume;private Display display;private Displayable displayable;public Helloworld() {display = Display.getDisplay(this);pauseCanvas=new MyPauseCanvas();getCanvasDisplay();// create the commands for both the gameCanvas and pauseCanvasexit=new Command("Exit",Command.EXIT,1);pause=new Command("Pause",Command.ITEM,2);gameCanvas.addCommand(exit);gameCanvas.addCommand(pause);gameCanvas.setCommandListener(this);resume=new Command("Resume",Command.ITEM,2);pauseCanvas.addCommand(resume);HELLOWORLD, TURBO EDITION49pauseCanvas.setCommandListener(this);}protected void startApp() throws MIDletStateChangeException {getCanvasDisplay();display.setCurrent(displayable);}protected void pauseApp() {System.out.println("Pausing...");if(displayable!=null){display.setCurrent(displayable);}}public void destroyApp(boolean unconditional) {releaseResource();}private void releaseResource() {if(gameCanvas!=null){gameCanvas.stop();}}private void getCanvasDisplay(){try{if(gameCanvas==null){gameCanvas=new MyGameCanvas(this);}if(!gameCanvas.isRunning()){gameCanvas.start();}displayable=gameCanvas;}catch(IOException ioe){}}public void commandAction(Command command, Displayable d){if (command==exit){releaseResource();notifyDestroyed();}else if (command==pause){displayable=pauseCanvas;releaseResource();notifyPaused();}else if(command==resume){try{startApp();}catch (MIDletStateChangeException msce){}}}}2.2.3GameCanvas Class: MyGameCanvas.javaWhereas the Helloworld.java class might be described as the heartbeat of this application, the MyGameCanvas.java class is probably thebrains behind the operation! It is called at the very beginning of execution50GETTING STARTEDby the MIDlet and it only stops ”thinking” when the MIDlet is pausedor destroyed.MyGameCanvas is responsible for instigating a thread that providesanimation to the current display.

However, prior to that it loads thegraphics from the resource directory within the MIDlet suite; these arethen used to form the sprite object, MySprite.java. A LayerManager,also created by the game canvas, manages this sprite object. As eachsprite is created, it is added to the layer manager’s index.Once the thread is up and running, having been started by thestartApp() method of the MIDlet, it is responsible through each cyclefor painting sprites to the screen and making sure that the correct spriteframe is ready to be displayed at the correct time. The thread actuallyleaves the frame management to the sprite itself, but we shall look at thislater.

The layer manager makes a call to its own graphics context and drawsthe sprites to the screen. This cycle creates the illusion that is animation.This process can be seen in the code below. The run() methodprovides the engine room for the thread cycle. First, it draws all theobjects in its graphics context to the screen, using the draw() method.draw() receives the graphics context from the thread and uses it tocreate a black rectangular background the size of the screen dimensions.Having calculated the center of the screen, it then uses the layer managerto also paint the sprites within its index to the screen and makes the callto the flushGraphics() method, which notifies the screen that thegraphics are ready for drawing and that they should be drawn now.Before resting for a short while, a call is made to the tick() method,which asks the sprite to manage which frame should be displayed next.This interface needs to remain the same if any changes are made to theunderlying logic that determines the frame display.import javax.microedition.lcdui.game.*;import javax.microedition.lcdui.*;import java.io.IOException;public class MyGameCanvas extends GameCanvas implements Runnable {private Command exit;private Helloworld midlet;private MySprite sprite;private LayerManager layerManager;private Thread thread;private boolean running;private final int SLEEP = 100;public MyGameCanvas(Helloworld midlet) throws IOException {super(true);this.midlet = midlet;sprite = createSprite();// initialize the layer managerlayerManager = new LayerManager();// append the sprite to the layer managerlayerManager.append(sprite);}HELLOWORLD, TURBO EDITION51public boolean isRunning(){return running;}synchronized void start(){running=true;thread=new Thread(this);thread.start();}public void run(){Graphics graphics=getGraphics();try{while (running){draw(graphics);tick();Thread.sleep(SLEEP);}}catch(InterruptedException ie){System.out.println(ie.toString());}}synchronized void stop(){running=false;}private void tick(){sprite.tick();}private void draw(Graphics g){// calculate the center of the screen based upon the// the images and canvas sizeint x = (getWidth()/2-sprite.getWidth()/2);int y = (getHeight()/2-sprite.getHeight()/2);// set and draw the backgroundg.setColor(0,0,0);g.fillRect(0,0,getWidth(),getHeight());// paint the sprite on the screenlayerManager.paint(g,x,y);flushGraphics();}private MySprite createSprite(){Image image=null;int height=0;int width=0;try{image = Image.createImage("/Splash.png");width = image.getWidth();height = image.getHeight() / MySprite.RAW_FRAMES;}catch(IOException io){io.printStackTrace();}return new MySprite(image, width, height);}}2.2.4 Sprite Class: MySprite.javaWhile the metaphor of the body is being used to describe this application,this class most probably represents a limb! It is a relatively simple class,52GETTING STARTEDbut it is clever enough to recognize what it is and act according tothe information it has at its disposal.

It subclasses the Game API classSprite, which is itself an extension of Layer.In order to make our GameCanvas as flexible as possible we needto make MySprite.java an intelligent class so that it can morphaccording to what it is holding – in other words, it reacts to the framesit has at its disposal. This is best achieved by making it responsible formaking sure the correct frame is current when the game canvas cyclesthrough its loop.Upon initialization, the object is passed some basic information aboutitself. First, it is told what image to use.

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

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

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

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