You are on page 1of 13

UNIDADES TECNOLGICAS DE SANTANDER INGENIERIA DE TELECOMUNICACIONES Crear un proyecto nuevo en NetBeans desde "Archivo > Proyecto Nuevo >

Categoras: Java ME > Proyectos: Mobile Application".

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.

PROGRAMACION DISPOSITIVOS MOVILES

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.

Aadir un MIDlet Canvas al proyecto


Si se parte de un proyecto bsico de una "Mobile Application", se debe aadir al paquete de fuentes un nuevo "MIDP Canvas". Para ello, hay que hacer clic con el botn derecho sobre el paquete "hello" y seleccin la opcin "Nuevo > MIDP Canvas". Si no se ha utilizado anteriormente, se debe buscar este tipo de elemento en la seccin "Otros > Categoras: MIDP > Tipo de Archivos: MIDP Canvas".

En este ejemplo se le va a asignar el nombre "Canvas1" al MIDP Canvas recin creado.

Crear un objeto Canvas


En el cdigo fuente del MIDlet que vaya a abrir el Canvas se debe crear un objeto de la clase del MIDP Canvas que se ha creado. Ya que el nombre del objeto se va a utilizar en varias partes del cdigo, se debe definir la variable como un atributo de clase, es decir, se debe declarar bajo la declaracin de la clase, fuera de cualquier mtodo. En este ejemplo se le va a dar el nombre "canvas1" a la variable, utilizando la sentencia:
Canvas1 canvas1;

En el mtodo constructor del MIDlet se puede crear el objeto del Canvas, con el cdigo:
canvas1 = new Canvas1();

PROGRAMACION DISPOSITIVOS MOVILES

UNIDADES TECNOLGICAS DE SANTANDER INGENIERIA DE TELECOMUNICACIONES

Cdigo para mostrar el Canvas


Ahora es el momento de aadir un comando al MIDlet que se encargar de abrir el Canvas. Por ello, hay que cambiar a la pestaa Flow o Screen y arrastrar un "Ok Command" al form desde el que se desea llamar al Canvas.

PROGRAMACION DISPOSITIVOS MOVILES

UNIDADES TECNOLGICAS DE SANTANDER INGENIERIA DE TELECOMUNICACIONES

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);

PROGRAMACION DISPOSITIVOS MOVILES

UNIDADES TECNOLGICAS DE SANTANDER INGENIERIA DE TELECOMUNICACIONES

Prueba de primeros resultados


As ya es posible ejecutar la aplicacin, y al llegar a pulsar el botn Ok en el emulador del mvil, tras pasar por la pantalla de bienvenida, aparece el texto "Sample text" sobre el formulario con el texto "Welcome", por lo que puede que no se aprecie bien.

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); }

PROGRAMACION DISPOSITIVOS MOVILES

UNIDADES TECNOLGICAS DE SANTANDER INGENIERIA DE TELECOMUNICACIONES

Dibujar dentro del Canvas


Dentro del mtodo paint hay que escribir las lneas de cdigo que vayan a realizar el dibujo deseado, utilizando los mtodos de la clase Graphics, (del paquete javax.microedition, que vara ligeramente de la clase Graphics de Java SE) aplicndolos sobre el objeto g que recibe como parmetro el mtodo paint. Como ejemplo, se puede probar a dejar la pantalla en negro dibujando un rectngulo que la rellene totalmente, y escribir el texto anterior en color verde:
public void paint(Graphics g) { //Establecer color negro g.setColor(0,0,0); //Dibujar un rectngulo relleno en toda la pantalla g.fillRect(0, 0, getWidth(), getHeight()); //Establecer color verde g.setColor(0,255,0); //Escribir el texto de ejemplo en la posicin 0,0 g.drawString("Sample Text",0,0,Graphics.TOP|Graphics.LEFT); }

El resultado sera el siguiente:

PROGRAMACION DISPOSITIVOS MOVILES

UNIDADES TECNOLGICAS DE SANTANDER INGENIERIA DE TELECOMUNICACIONES

Detectar pulsaciones de teclas


La clase Canvas que se ha creado tambin dispone de un mtodo creado automticamente para detectar las pulsaciones de las teclas del mvil. Ese mtodo es el keyPressed que recibe como parmetro el cdigo de la tecla pulsada.
/** * Called when a key is pressed. */ protected void keyPressed(int keyCode) { }

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))) { ... }

En el siguiente ejemplo se muestra en la pantalla el texto correspondiente a cada tecla de direccin:


public class Canvas1 extends Canvas implements CommandListener { String texto = "Sample Text"; /** * constructor */ public Canvas1() { try { // Set up this canvas to listen to command events setCommandListener(this); // Add the Exit command addCommand(new Command("Exit", Command.EXIT, 1)); } catch(Exception e) { e.printStackTrace(); } } /** * paint */ public void paint(Graphics g) { //Establecer color negro g.setColor(0,0,0); //Dibujar un rectngulo relleno en toda la pantalla g.fillRect(0, 0, getWidth(), getHeight()); PROGRAMACION DISPOSITIVOS MOVILES

UNIDADES TECNOLGICAS DE SANTANDER INGENIERIA DE TELECOMUNICACIONES


//Establecer color verde g.setColor(0,255,0); //Escribir el texto de ejemplo en la posicin 0,0 g.drawString(texto,0,0,Graphics.TOP|Graphics.LEFT); } /** * Called when a key is pressed. */ protected void keyPressed(int keyCode) { if(keyCode == getKeyCode(UP)) { texto = "Arriba"; repaint(); } else if(keyCode == getKeyCode(DOWN)) { texto = "Abajo"; repaint(); } else if(keyCode == getKeyCode(RIGHT)) { texto = "Derecha"; repaint(); } else if(keyCode == getKeyCode(LEFT)) { texto = "Izquierda"; repaint(); } }

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.

Asignar cdigo al comando Exit


En la ejecucin anterior se puede comprobar que, al abrir el Canvas que se ha creado, aparece la posibilidad de utilizar un botn Exit, pero al pulsarlo no se produce nada. Esto es debido a que, al crear el Canzas desde NetBeans, se crea automticamente el cdigo necesario, en el mtodo constructor, para que aparezca el comando Exit, pero sin asignarle ningn cdigo ejecutable.
public Canvas1() { try { // Set up this canvas to listen to command events setCommandListener(this); // Add the Exit command addCommand(new Command("Exit", Command.EXIT, 1)); } catch(Exception e) { e.printStackTrace(); } }

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.

PROGRAMACION DISPOSITIVOS MOVILES

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

UNIDADES TECNOLGICAS DE SANTANDER INGENIERIA DE TELECOMUNICACIONES


x - the x coordinate of the upper-left corner of the arc to be drawn y - the y coordinate of the upper-left corner of the arc to be drawn width - the width of the arc to be drawn height - the height of the arc to be drawn startAngle - the beginning angle arcAngle - the angular extent of the arc, relative to the start angle

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

UNIDADES TECNOLGICAS DE SANTANDER INGENIERIA DE TELECOMUNICACIONES


width - the width of the rectangle to be drawn height - the height of the rectangle to be drawn arcWidth - the horizontal diameter of the arc at the four corners arcHeight - the vertical diameter of the arc at the four corners

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

PROGRAMACION DISPOSITIVOS MOVILES

13

You might also like