25
Java ME Elementos da interface gráfica Aula 2 Marcio Seiji Oyamada

Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

Embed Size (px)

Citation preview

Page 1: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

Java ME

Elementos da interface gráfica

Aula 2

Marcio Seiji Oyamada

Page 2: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 31

Classe Displayable

�É uma superclasse que define métodos básicos para qualquer classe que possa ser exibida na tela

�Métodos Importantes– addCommand(Command c)

• Adiciona um comando à tela Ex.: Sair, Abrir, Próxima Janela etc.

– setCommandListener(CommandListener l)

• informa o objeto responsável por receber os eventos gerados por comandos na tela atual

– boolean isShown()

• informa se o componente está sendo visto na tela no momento

Page 3: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 32

Pacotes lcdui e lcdui.game

Page 4: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 33

Page 5: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 34

Screen

� Classe abstrata: interface de alto nível

� No MIDP são oferecidos quatro tipos– Caixa de texto

– Alerta

– Listas

– Formulário

� Para mostrar uma screen é necessário obter o “Display” do dispositivo

Display.getDisplay(this).setCurrent(nextScreen1)

Display.getDisplay(this).setCurrent(alert, nextScreen1)

Page 6: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 35

TextBox

�Caixa de Texto: utilizado para entrada de dados– public TextBox(String title, String text, int maxSize, int constraints)

– Deve ser utilizado com cuidado, pois a inclusão de dados em dispositivos móveis é uma tarefa complicada

�Constraints– Qualquer texto: ANY

– E-mail: EMAILADDR

– Somente números inteiros: NUMERIC

– Telefone: PHONENUMBER

– Link para web: URL

– Números decimais: DECIMAL

Page 7: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 36

TextBox: Exemplo

import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

public class MidletTextBox extends MIDlet {

Display myDisplay;

TextBox d = new TextBox("TextBox", "Commander", 20, TextField.ANY);

public void startApp() {

myDisplay= Display.getDisplay(this);

myDisplay.setCurrent(d);

}

public void pauseApp() {

}

public void destroyApp(boolean unconditional) {

}

}

Page 8: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 37

Comandos

�Command

– Objetos invocados pelo usuário: analogia Botão

– Obter uma resposta do usuário

• A forma será determinada pelo dispositivo: teclado, botão, voz, etc

– Todo objeto Displayable contém uma lista de comandos

• Adicionar: addCommand(Command cmd)

• Remover: removeCommand(Command cmd)

�Construtor– Command c = new Command("OK", Command.OK, 0);

– Rótulo, Tipo, Prioridade

Page 9: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 38

Comandos: tipos e prioridades

�O posicionamento dos comandos é determinado pela JavaME de acordo com o tipo, prioridade e a disponibilidade de espaço na tela.

�Tipos– OK

– CANCEL

– BACK

– STOP

– HELP

– SCREEN: genérico

�Prioridades: a prioridade define quais serão os comandos que serão apresentados caso não exista espaço suficiente na tela ( 0 é a menor prioridade)

Page 10: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 39

CommandListener

�Modelo de delegação (SWING): Command é o elemento visual. Um listener é o objeto responsável por tratar os eventos do comando

�Um objeto Displayable dispara todos os eventos dos comandos – É necessário cadastrar um único CommandListener

– Método: public void setCommandListener(CommandListener l)

�CommandListener interface– Método: public void commandAction(Command c, Displayable s)

Page 11: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 40

Exemplo: CommandListener

public class MidletTextBox extends MIDlet {

Display myDisplay;

TextBox d= new TextBox("TextBox", "Commander", 20, TextField.ANY);

Command exit= new Command("Exit", Command.EXIT,0);

public void startApp() {

myDisplay= Display.getDisplay(this);

d.addCommand(exit);

d.setCommandListener(new CommandListener(){

public void commandAction(Command arg0, Displayable arg1) {

notifyDestroyed();

}

});

myDisplay.setCurrent(d);

}

public void pauseApp() {

}

public void destroyApp(boolean unconditional) {

}

}

Page 12: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 41

Exemplo: CommandListener

public class MidletTextBox extends MIDlet {

Display myDisplay;

TextBox d= new TextBox("TextBox", "Commander", 20, TextField.ANY);

Command exit= new Command("Exit", Command.EXIT,0);

public void startApp() {

myDisplay= Display.getDisplay(this);

d.addCommand(exit);

d.setCommandListener(new CommandListener(){

public void commandAction(Command arg0, Displayable arg1) {

notifyDestroyed();

}

});

myDisplay.setCurrent(d);

}

public void pauseApp() {

}

public void destroyApp(boolean unconditional) {

}

}

Page 13: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 42

Exemplo: CommandListener

public class MidletTextBox extends MIDlet {

Display myDisplay;

Displayable d;

public void startApp() {

myDisplay= Display.getDisplay(this);

d = new TextBox("TextBox", "Commander", 20, TextField.ANY);

Command exit= new Command("Exit", Command.EXIT,0);

d.addCommand(exit);

d.setCommandListener(new CommandListener(){

public void commandAction(Command arg0, Displayable arg1) {

notifyDestroyed();

}

});

myDisplay.setCurrent(d);

}

public void pauseApp() {

}

public void destroyApp(boolean unconditional) {

}

}

Page 14: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 43

Exemplo 2

public class MidletTextBox extends MIDlet {

Display myDisplay;

Command exit= new Command("Exit", Command.EXIT,0);

Command clear= new Command("Clear",Command.SCREEN, 0);

TextBox d = new TextBox("TextBox", "Commander", 20, TextField.ANY);

public void startApp() {

myDisplay= Display.getDisplay(this);

d.addCommand(exit);

d.addCommand(clear);

d.setCommandListener(new CommandListener(){

public void commandAction(Command arg0, Displayable arg1) {

if (arg0== exit){

notifyDestroyed();

}else if (arg0==clear){

d.setString("");

}

}

});

myDisplay.setCurrent(d);

}

public void pauseApp() { }public void destroyApp(boolean unconditional) { }

Page 15: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 44

List

�Uma lista com itens a serem selecionados

– As listas podem ser de 3 tipos:

– EXCLUSIVE: uma seleção por vez

– MULTIPLE: permite várias seleções por vez

– IMPLICIT: quando uma opção é selecionada é disparado um novo comando

�Utilizar quando possível, pois facilita a entrada de dados

�Construtor

– List(“Reservas", List.IMPLICIT,stringElements, imageElements);

Page 16: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 45

List: Exemplo EXCLUSIVE

public class ListMIDlet extends MIDlet implements CommandListener {

private boolean midletPaused = false;

private List mlist;

private Command Next= new Command("Next",Command.OK,0);

private Command Cancel= new Command("Cancel", Command.CANCEL, 0);

private StringItem stringItem;

public startMIDlet() {

String[] elements= {"Maringa", "Curitiba", "Porto Alegre"};

Image[] images= {null, null, null};

mlist= new List("Origem", List.EXCLUSIVE, elements, images);

mlist.addCommand(Next);

mlist.addCommand(Cancel);

mlist.setCommandListener(new CommandListener() {

public void commandAction(Command arg0, Displayable arg1) {

if (arg0== Cancel) {

notifyDestroyed();

}

else if (arg0== Next){

notifyDestroyed();

}

}

});

}

Page 17: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 46

List: Exemplo EXCLUSIVE(2)

Page 18: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 47

List: Exemplo MULTIPLE

public class ListMIDlet extends MIDlet implements CommandListener {

private boolean midletPaused = false;

private List mlist;

private Command Next= new Command("Next",Command.OK,0);

private Command Cancel= new Command("Cancel", Command.CANCEL, 0);

private StringItem stringItem;

public startMIDlet() {

String[] elements= {“Projeto”, “Implementação”, “Suporte”};

Image[] images= {null, null, null};

mlist= new List(“Areas", List.EXCLUSIVE, elements, images);

mlist.addCommand(Next);

mlist.addCommand(Cancel);

mlist.setCommandListener(new CommandListener() {

public void commandAction(Command arg0, Displayable arg1) {

if (arg0== Cancel) {

notifyDestroyed();

}

else if (arg0== Next){

notifyDestroyed();

}

}

});

}

Page 19: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 48

List: Exemplo MULTIPLE (2)

Page 20: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 49

Listas: Seleção

�Obtendo os elementos selecionados em uma lista– public boolean isSelected(int index)

– public int getSelectedFlags(boolean[] selectedArray_return)

�Para listas IMPLICIT e EXCLUSIVE

– public int getSelected()

– Retorna –1 se a lista é do tipo MULTIPLE

�Alterando a lista– public void setSelectedIndex(int index, boolean flag)

Page 21: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 50

Alert

�Utilizado para mostrar informações para o usuário, podendo ser de dois tipos:

– TIMED: o alerta é apresentado por uma certa quantia de tempo(geralmente segundos), e depois fechado

– MODAL: o alerta é apresentado e deve ser fechado explicitamente através de um comando do usuário

�Construtor

– public Alert(String title, String alertText, Image alertImage, AlertType alertType)

Page 22: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 51

Alert: tipos e timeout

�Tipos de alerta

– ALARM, CONFIRMATION, ERROR, INFO e WARNING

– A implementação MIDP pode utilizar o tipo para definir o som que serátocado quando o alerta for apresentado

�Um alerta tem um timeout pré-definido

– alert.getDefaultTimeout();

�Para alterar o timeout

– alert.setTimeout(5000); // 5 segundos

– alert.setTimeout(Alert.FOREVER); // modal

Page 23: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 52

Exemplo Alert

public class AlertExample extends MIDlet {

TextBox tb= new TextBox("Inicial", "", 10, TextField.ANY);

Alert alertAbout= new Alert("About", "Este é um aplicativo para testar o alerta",null, AlertType.INFO);

Alert alertNotImplemented;

Command cExit = new Command("Exit", Command.EXIT, 0);

Command cGo = new Command("Go!", Command.SCREEN, 0);

Command cAbout= new Command("About", Command.SCREEN, 1);

Display d;

public void startApp() {

try {

d = Display.getDisplay(this);

alertNotImplemented = new Alert("Not Implemented", "Esta funcionalidade ainda

não foi implementada", Image.createImage("/stop.png"), AlertType.ERROR);

tb.addCommand(cExit);

tb.addCommand(cGo);

tb.addCommand(cAbout);

alertNotImplemented.setTimeout(2000);

alertAbout.setTimeout(Alert.FOREVER);

Page 24: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 53

Exemplo Alert(2)

Continuação do método startMIDlet()

tb.setCommandListener(new CommandListener() {

public void commandAction(Command c, Displayable s) {

if (c == cGo) {

d.setCurrent(alertNotImplemented, tb);

} else if (c == cAbout) {

d.setCurrent(alertAbout, tb);

} else if (c == cExit) {

notifyDestroyed();

}

}

});

d.setCurrent(tb);

} catch (IOException ex) {

ex.printStackTrace();

}

}

Page 25: Java ME Elementos da interface gráfica Aula 2marcio/JavaME/JavaMEAula2.pdf · Page 34 IWS'2009 - Buenos Aires Screen Classe abstrata: interface de alto n ível No MIDP são oferecidos

IWS'2009 - Buenos AiresPage � 54

Exercício

1) Inclua 4 botões em um TextBox. Verique como o MIDP gerencia o posicionamento dos botões

2) Implemente um MIDLET que retorna o número de pedágios e os valores entre duas cidades

a) Considere as seguintes cidades: Foz do Iguaçu, Cascavel, Maringá, Londrina, Curitiba

b) As informações (pedágios e valores) deverão ser armazenadas em objetos dentro do MIDlet (não recomendável)