Professional Documents
Culture Documents
Asignar nombre al proyecto. Por ejemplo, "HolaMundo". Hacer clic en "Terminar" o pasar por el resto de las pantallas dejando la opcin por defecto. Tras crearse el proyecto se muestra la pantalla en la que se podrn realizar modificaciones sobre la aplicacin, tanto visualmente como desde el cdigo fuente. La aplicacin se crea automticamente para que muestre el mensaje "Hello, World" en el terminal mvil.
Para probar el funcionamiento en el emulador de telfono mvil, ejecutar el proyecto: "Ejecutar > Ejecutar Main Project".
PROGRAMACION DISPOSITIVOS MOVILES
UNIDADES TECNOLGICAS DE SANTANDER INGENIERIA DE TELECOMUNICACIONES Se abre el emulador del mvil, y se muestra en la pantalla el nombre de la aplicacin.
Haciendo clic en el botn que aparece bajo "Launch" en el mvil, se arrancar la aplicacin.
UNIDADES TECNOLGICAS DE SANTANDER INGENIERIA DE TELECOMUNICACIONES El diseo de aplicaciones para mviles desde NetBeans se facilita mucho con el diseo visual a travs del "Flow" si se trata de enlazar los elementos "Displayables" que se ofrecen en la "Paleta". Pero si se pretende mostrar una pantalla en la que se presenten grficos de la clase "Graphics", se debe emplear un "MIDP Canvas" que no aparece en la paleta y que no se puede enlazar con otras pantallas de forma visual.
En el mtodo constructor del MIDlet se puede crear el objeto del Canvas, con el cdigo:
canvas1 = new Canvas1();
Para asignar el cdigo fuente necesario al comando Ok, hay que volver a la pestaa "Source" y buscar el mtodo "CommandAction" que se encontrar oculto y habr que desplegarlo para ver su contenido. Tras la lnea donde se comprueba que se ha pulsado el comando Ok, se insertar el cdigo necesario. Es decir detrs de la lnea:
else if (command == okCommand) {
La sentencia que permite abrir una determinada pantalla sigue el siguiente formato:
Display.getDisplay(this).setCurrent(nombreDeLaPantalla);
Donde nombreDeLaPantalla debe ser el nombre de la variable que hace referencia a la pantalla que se desea mostrar. En este caso es "canvas1", por lo que la lnea debe quedar as:
Display.getDisplay(this).setCurrent(canvas1);
La razn por la que se muestra el texto "Sample text" se puede ver en el cdigo autogenerado del Canvas. En la pestaa Source del Canvas1 se puede observar la lnea correspondiente dentro del mtodo paint.
public void paint(Graphics g) { g.drawString("Sample Text",0,0,Graphics.TOP|Graphics.LEFT); }
Para realizar una determinada accin en funcin de la tecla pulsada hay que consultar el valor que recoge el parmetro keyCode. La clase Canvas dispone de una serie de constantes predefinidas para distinguir las teclas numricas del teclado (KEY_NUM0, KEY_NUM1, etc.). En esos casos se puede hacer la comparacin directamente del keyCode con esas constantes. por ejemplo:
if(keyCode == KEY_NUM1)) { ... }
Pero para detectar las pulsaciones de las teclas de direccin se debe hacer la comparacin utilizando el mtodo getKeyCode pasndole como parmetro una de las constantes de direccin (UP, DOWN, LEFT, RIGHT), por ejemplo:
if(keyCode == getKeyCode(UP))) { ... }
Se puede observar en el ejemplo anterior que para que el texto sea mostrado se ha declarado una variable llamada texto, como atributo de la clase, y se ha incluido en la sentencia drawString para que se muestre el texto que contenga dicha variable. La llamada al mtodo repaint() en cada caso, hace que el mtodo paint() del Canvas sea de nuevo ejecutado, redibujando el texto que es mostrado.
Como se puede observar, se crea un comando de tipo EXIT. Por tanto, en el mtodo commandAction podemos preguntar si el comando que ha sido activado es de ese tipo, en cuyo caso se volver a mostrar el MIDlet anterior. El hecho de quere mostrar el MIDlet anterior ocasiona que en la clase del Canvas necesitemos una referencia al MIDlet que lo ha creado para retornar a l la visibilidad. Para solucionar esto se puede
PROGRAMACION DISPOSITIVOS MOVILES
UNIDADES TECNOLGICAS DE SANTANDER INGENIERIA DE TELECOMUNICACIONES crear un atributo en la clase del Canvas para guardar la referencia al MIDlet (en el ejempo se llamar midletAnterior).
public class Canvas1 extends Canvas implements CommandListener { String texto = "Sample Text"; HelloMIDlet midletAnterior;
Al mtodo constructor del Canvas se le pasar un parmetro con la referencia al MIDlet que lo ha creado, el cual ser guardado en el atributo midletAnterior.
public Canvas1(HelloMIDlet midletAnterior) { try { // Set up this canvas to listen to command events setCommandListener(this); // Add the Exit command addCommand(new Command("Exit", Command.EXIT, 1)); //Guardar la referencia al MIDlet que ha creado este Canvas this.midletAnterior = midletAnterior; } catch(Exception e) { e.printStackTrace(); } }
De esta forma, se puede indicar en el comando Exit que se muestre nuevamente el form que hay creado en midletAnterior.
public void commandAction(Command command, Displayable displayable) { if(command.getCommandType() == Command.EXIT) Display.getDisplay(midletAnterior).setCurrent(midletAnterior.g etForm()); }
Al haber modificado el mtodo constructor del Canvas aadindole un parmetro, nos encontraremos con un error en la clase del MIDlet en el lugar donde se creaba el objeto del Canvas. Hasta ahora no se le pasaba ningn parmetro, y ahora hay que indicar la clase que est creando el Canvas. Por ello se le pasa por parmetro el objeto this.
public HelloMIDlet() { canvas1 = new Canvas1(this); }
Listado de Comando de Grficos. 1. fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle)
Fills a circular or elliptical arc covering the specified rectangle. The resulting arc begins at startAngle and extends for arcAngle degrees. Angles are interpreted such that 0 degrees is at the 3 o'clock position. A positive value indicates a counter-clockwise rotation while a negative value indicates a clockwise rotation.
10
UNIDADES TECNOLGICAS DE SANTANDER INGENIERIA DE TELECOMUNICACIONES The center of the arc is the center of the rectangle whose origin is (x, y) and whose size is specified by the width and height arguments. If either width or height is zero or less, nothing is drawn. 2. fillRect(int x, int y, int width, int height) Fills the specified rectangle with the current color. If either width or height is zero or less, nothing is drawn. Parameters: x - the x coordinate of the rectangle to be filled y - the y coordinate of the rectangle to be filled width - the width of the rectangle to be filled height - the height of the rectangle to be filled 3. fillRoundRect(int x, int y, int width, int height, int arcWidth,
int arcHeight)
height
Fills the specified rounded corner rectangle with the current color. If either width or is zero or less, nothing is drawn.
Parameters: x - the x coordinate of the rectangle to be filled y - the y coordinate of the rectangle to be filled width - the width of the rectangle to be filled height - the height of the rectangle to be filled arcWidth - the horizontal diameter of the arc at the four corners arcHeight - the vertical diameter of the arc at the four corners 4. fillTriangle(int x1, int y1, int x2, int y2, int x3, int y3) Fills the specified triangle will the current color. The lines connecting each pair of points are included in the filled triangle. Parameters: x1 - the x coordinate of the first vertex of the triangle y1 - the y coordinate of the first vertex of the triangle x2 - the x coordinate of the second vertex of the triangle y2 - the y coordinate of the second vertex of the triangle x3 - the x coordinate of the third vertex of the triangle y3 - the y coordinate of the third vertex of the triangle 5. drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle)
Draws the outline of a circular or elliptical arc covering the specified rectangle, using the current color and stroke style. Parameters:
PROGRAMACION DISPOSITIVOS MOVILES
11
6. drawChar(char character, int x, int y, int anchor) Draws the specified character using the current font and color. Parameters:
character - the character to be drawn x - the x coordinate of the anchor point y - the y coordinate of the anchor point anchor - the anchor point for positioning the text;
7. drawLine(int x1, int y1, int x2, int y2) Draws a line between the coordinates (x1,y1) and (x2,y2) using the current color and stroke style. Parameters: x1 - the x coordinate of the start of the line y1 - the y coordinate of the start of the line x2 - the x coordinate of the end of the line y2 - the y coordinate of the end of the line 8. drawRect(int x, int y, int width, int height) Draws the outline of the specified rectangle using the current color and stroke style. The resulting rectangle will cover an area (width + 1) pixels wide by (height + 1) pixels tall. If either width or height is less than zero, nothing is drawn. Parameters: x - the x coordinate of the rectangle to be drawn y - the y coordinate of the rectangle to be drawn width - the width of the rectangle to be drawn height - the height of the rectangle to be drawn 9. drawRoundRect(int x, int y, int width, int height, int arcWidth,
int arcHeight)
Draws the outline of the specified rounded corner rectangle using the current color and stroke style. The resulting rectangle will cover an area (width + 1) pixels wide by (height + 1) pixels tall. If either width or height is less than zero, nothing is drawn. Parameters: x - the x coordinate of the rectangle to be drawn y - the y coordinate of the rectangle to be drawn
PROGRAMACION DISPOSITIVOS MOVILES
12
10. drawString(String str, int x, int y, int anchor) Draws the specified String using the current font and color. The x,y position is the position of the anchor point. See anchor points. Parameters: str - the String to be drawn x - the x coordinate of the anchor point y - the y coordinate of the anchor point anchor - the anchor point for positioning the text 11. setColor(int red, int green, int blue) Sets the current color to the specified RGB values. All subsequent rendering operations will use this specified color. Parameters: red - the red component of the color being set in range 0-255 green - the green component of the color being set in range 0-255 blue - the blue component of the color being set in range 0-255
13