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

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

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

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

Adds Commands and a ChoiceGroup.public ChoiceForm(GameMIDlet midlet){super("Saved Images");this.midlet = midlet;startCommand = new Command("Start" , Command.SCREEN , 2);deleteCommand = new Command("Delete" , Command.SCREEN , 3);exitCommand = new Command("Exit", Command.EXIT, 1);addCommand(exitCommand);addCommand(startCommand);setCommandListener(this);cg = new ChoiceGroup("Choose image option:",ChoiceGroup.EXCLUSIVE);append(cg);cg.append("Create new image", null);}//Adds the names of the stored images to the ChoiceGroup.public void setImageNames(String[] imageNames) {while( cg.size() > 1 ){cg.delete(1);}cg.setSelectedIndex(0, true);if (imageNames != null) {for (int i = 0 ; i < imageNames.length ; i++) {cg.append(imageNames[i] , null);}addCommand(deleteCommand);}}public void commandAction(Command command , Displayable displayable) {if (command == exitCommand) {midlet.exit();} else if(command == startCommand) {if (cg.getSelectedIndex() == 0) {midlet.displayCaptureCanvas();}else {String imageName = cg.getString(cg.getSelectedIndex());midlet.loadAndDisplayImage(imageName);}}else if(command == deleteCommand) {int index = cg.getSelectedIndex();if(index > 0) {String imageName = cg.getString(index);cg.setSelectedIndex(index - 1, true);cg.delete(index);midlet.deleteImage(imageName);}if(cg.size() == 1) {removeCommand(deleteCommand);}}}}This uses a ChoiceGroup to display the names of any previousimages stored by the user or allows the user to capture a new image.302MIDP 2.0 CASE STUDIESIf the user selects the ‘‘Create new image’’ option the ChoiceForminstance calls the displayCaptureCanvas() method of GameMIDlet (listed below).public void displayCaptureCanvas() {if (captureCanvas == null) {//create CaptureCanvas and associated playercaptureCanvas = new CaptureCanvas(this);try{capturer = new Capturer(this, captureCanvas);capturer.startPlayer();display.setCurrent(captureCanvas);}catch(final ApplicationException ae){//set to null if unable to create playercaptureCanvas = null;showAlert(ae);}} else {//CaptureCanvas and associated player already existdisplay.setCurrent(captureCanvas);}}This creates an instance of the Capturer class encapsulating a VideoPlayer and an associated Canvas to display the output.

It then calls thestartPlayer() method of the Capturer class to start the VideoPlayer which renders the output of the phone’s camera to the Canvas.5.4.3The Capturer Classpackage picturepuzzle;import javax.microedition.media.*;import javax.microedition.media.control.*;import java.io.IOException;// Creates the VideoPlayer used to capture a photo.public class Capturer {privateprivateprivateprivateprivateGameMIDlet midlet;CaptureCanvas canvas;Player player = null;VideoControl videoControl = null;boolean active = false;// Performs initialization and creates the VideoPlayer instance.public Capturer(GameMIDlet midlet, CaptureCanvas canvas)throws ApplicationException {this.midlet = midlet;this.canvas = canvas;createPlayer();}// Creates a VideoPlayer and gets an associated VideoControlpublic void createPlayer() throws ApplicationException {THE PICTURE PUZZLE303try {player = Manager.createPlayer("capture://video");player.realize();// Sets VideoControl to the current display.videoControl =(VideoControl)(player.getControl("VideoControl"));if (videoControl == null) {discardPlayer();} else {videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO,canvas);int cWidth = canvas.getWidth();int cHeight = canvas.getHeight();int dWidth = 160;int dHeight = 120;videoControl.setDisplaySize(dWidth, dHeight);videoControl.setDisplayLocation((cWidth - dWidth)/2,(cHeight - dHeight)/2);}} catch (IOException ioe) {discardPlayer();throw new ApplicationException("Unable to access camera",ioe);} catch (MediaException me) {discardPlayer();throw new ApplicationException("Unable to access camera", me);} catch(SecurityException se) {discardPlayer();throw new ApplicationException("Unable to access camera", se);}}public byte[] takeSnapshot() throws ApplicationException {byte[] pngImage = null;if (videoControl == null) {throw new ApplicationException("Unable to capture photo: VideoControl null");}try {pngImage = videoControl.getSnapshot(null);}catch(MediaException me) {throw new ApplicationException("Unable to capture photo", me);}return pngImage;}public void discardPlayer() {if(player != null) {player.close();player = null;}videoControl = null;}public void startPlayer() throws ApplicationException {if ((player != null) && !active) {304MIDP 2.0 CASE STUDIEStry {player.start();videoControl.setVisible(true);} catch(MediaException me) {throw new ApplicationException("Unable to start video player", me);} catch(SecurityException se) {throw new ApplicationException("Unable to start video player", se);}active = true;}}public void stopPlayer() throws ApplicationException {if ((player != null) && active) {try {videoControl.setVisible(false);player.stop();} catch (MediaException me) {throw new ApplicationException("Unable to stop video player", me);}active = false;}}}The creation and initialization of the VideoPlayer takes place inthe createPlayer() method.

We use the static createPlayer()method of Manager to create the VideoPlayer instance using thecapture://video URI to indicate that the data source is the phone’scamera. Next we call the realize() method to move the player to theREALIZED state. We then get a VideoControl and initialize it with ourCaptureCanvas instance.The photo is taken using the takeSnapshot() method. It calls theVideoControl.getSnapshot() method which takes a snapshot ofthe current contents of the display and returns it as a PNG image.

ThetakeSnapshot() method is called from the CaptureCanvas object.5.4.4The CaptureCanvas Classpackage picturepuzzle;import javax.microedition.lcdui.*;/*** A Canvas for rendering the output of the VideoPlayer. Also handles the* user interaction to take the snapshot.*/public class CaptureCanvas extends Canvas implements CommandListener{private Command captureCommand;private GameMIDlet midlet;THE PICTURE PUZZLE305//Creates the CaptureCanvas.

Adds a "Capture" command.public CaptureCanvas(GameMIDlet midlet){this.midlet = midlet;captureCommand = new Command("Capture", Command.SCREEN, 1);addCommand(captureCommand);setCommandListener(this);}// Paints a yellow background.public void paint(Graphics g) {g.setColor(0x00FFFF00); // yellowg.fillRect(0, 0, getWidth(), getHeight());}//Responds to the "Capture" command and takes the photo.public void commandAction(Command command , Displayable displayable) {if(command == captureCommand){midlet.takePhoto();}}//Responds to the Joystick being pressed and takes the photo.public void keyPressed(int keyCode) {int key = getGameAction(keyCode);if (key == Canvas.FIRE) {midlet.takePhoto();}}}The CaptureCanvas class provides the Canvas onto which theoutput of the camera is rendered.

When the user is satisfied with thescene, the snapshot is taken by selecting the ‘‘Capture’’ Command. ThecommandAction() method makes a call back to the GameMIDlettakePhoto() method:public void takePhoto(){try {byte[] data = capturer.takeSnapshot();capturer.stopPlayer();ImageNameBox imageNameBox = new ImageNameBox(this, data);display.setCurrent(imageNameBox);}catch(final ApplicationException ae) {showAlert(ae);}This calls the takeSnapshot() method of the Capturer, whichreturns the captured image data. Once the photo has been taken theVideoPlayer is then stopped using the stopPlayer() method. Aninstance of ImageNameBox is created to enable the user to associate aname with the new image.3065.4.5MIDP 2.0 CASE STUDIESThe ImageNameBox ClassImageNameBox extends TextBox and provides an area into which theuser can enter a name for the new image.package picturepuzzle;import javax.microedition.lcdui.*;public class ImageNameBox extends TextBox implements CommandListener {private GameMIDlet midlet;private byte[] data;private Command saveCommand;public ImageNameBox(GameMIDlet midlet, byte[] data) {super("Enter image name", "", 20, TextField.ANY);this.midlet = midlet;this.data = data;saveCommand = new Command("Save" , Command.SCREEN , 2);setCommandListener(this);addCommand(saveCommand);}public void commandAction(Command command , Displayable displayable) {if (command == saveCommand) {midlet.saveImage(getString(), data);midlet.displayPuzzleCanvas(image);}}}When the user selects the ‘‘Save’’ command, the image data and nameare saved to the RMS store via a call to the GameMIDlet saveImage() method.

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

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

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

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