Vous êtes sur la page 1sur 60

Programação Comercial

GUI Components

1 Stephenson Galvão
sgalvao@ifpi.edu.br
Aula Passada
● Caixa de Dialgo
– JOptionPane
● Mensagem
● Escola
● Entrada

2 Stephenson Galvão
sgalvao@ifpi.edu.br
Aula de Hoje
● Interface Gráficas Robusta

3 Stephenson Galvão
sgalvao@ifpi.edu.br
Swing x AWT
● Existem dois tipos de componentes GUI
– Abstract Window Toolkit ( AWT): java.awt
● Componentes que interagem com o sistema
– Pegando sua aparencia e comportamento
● São exibidas de forma direfentes em cada S.O.

– Swing: javax.swing
● Componente mais simples e portáveis.

4 Stephenson Galvão
sgalvao@ifpi.edu.br
Hierarquia de Componentes
● Component: declara características
comuns dos componentes GUI.
Component
● Container: agrupa componentes e
organiza-os
● JComponent: Características
Container comuns aos componetes Swing,
– Pluggable look-and-feel
– Shortcut keys
– Tool tips
JComponent
– Acessibilidade
– Internacionalização

5 Stephenson Galvão
sgalvao@ifpi.edu.br
Exibindo Texto e Imagens
● Criando Janelas
– Os componentes swings são exibidos dentro de
janelas.
– Janelas são instâncias de classe JFrame ou de
subclasse de JFrame.
– JFrame:
● Subclasse indireta da classe java.awt.Window que
fornece os atributos e comportamentos de uma janela:
– a title bar no topo
– botões para minimizar, maximizar e fechar.

6 Stephenson Galvão
sgalvao@ifpi.edu.br
Exemplo
● Criando um JFrame
Declaração do import javax.swing.JFrame; Criação do obejto.
objeto instanciação
public class Ola {
public static void main(String[] args) {
JFrame meuFrame;
meuFrame = new JFrame("Meu Frame");
meuFrame.setVisible(true);
}
}

Tornando o objeto
visível.

7 Stephenson Galvão
sgalvao@ifpi.edu.br
Execução
Faça você mesmo.

import javax.swing.JFrame;
Tamanho do
Frame public class Ola {
public static void main(String[] args) {
JFrame meuFrame = new JFrame("Meu Frame");
meuFrame.setVisible(true);
meuFrame.setSize(400, 200);
}
}

8 Stephenson Galvão
sgalvao@ifpi.edu.br
Execução
Faça você mesmo.
Termina a execução
quando fechar o Frame.

import javax.swing.JFrame;
public class Ola {
public static void main(String[] args) {
JFrame meuFrame = new JFrame("Meu Frame");
meuFrame.setVisible(true);
meuFrame.setSize(400, 200);
meuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Após o teste, troque o argumento Jframe.EXIT_ON_CLOSE por


JFrame.DO_NOTHING_ON_CLOSE
9 Stephenson Galvão
sgalvao@ifpi.edu.br
Com Herança

import javax.swing.JFrame;
public class MeuFrame extends JFrame {
public MeuFrame() {
setTitle("Titulo Frame");
setSize(100,100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
public class App {
public static void main(String[] args) {
MeuFrame meuFrame = new MeuFrame();
meuFrame.setVisible(true);
}
}

10 Stephenson Galvão
sgalvao@ifpi.edu.br
JComponetes

11 Stephenson Galvão
sgalvao@ifpi.edu.br
Adicionando Componentes
● JLabel
– A área de exibição de uma seqüência curta de
texto ou uma imagem, ou ambos
Instanciando um
JLabel
Declarando um
JLabel
JLabel meuLabel = new JLabel();
meuLabel.setText("Meu Primeiro Label");

Colocando o texto do JLabel

12 Stephenson Galvão
sgalvao@ifpi.edu.br
Criando o JFrame
JLabel
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Ola {
public static void main(String[] args) {
JFrame meuFrame = new JFrame("Meu Frame");
meuFrame.setVisible(true);
meuFrame.setSize(400, 200);
meuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel meuLabel = new JLabel();
Criando o JLabel meuLabel.setText("Meu Primeiro Label");
meuFrame.add(meuLabel);
}
}
Adicionando o
JLabel ao Frame

13 Stephenson Galvão
sgalvao@ifpi.edu.br
Execução
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Ola {
public static void main(String[] args) {
JFrame meuFrame = new JFrame("Meu Frame");
meuFrame.setVisible(true);
meuFrame.setSize(400, 200);
meuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel meuLabel = new JLabel();
meuLabel.setText("Meu Primeiro Label");
meuFrame.add(meuLabel);
}
}

14 Stephenson Galvão
sgalvao@ifpi.edu.br
Com Herança

Componente declarado como


import javax.swing.JFrame;
campo do objeto para ser acessado
import javax.swing.JLabel; durante toda a classe.

public class MeuFrame extends JFrame {


private JLabel meuLabel;
public MeuFrame() {
setTitle("Titulo Frame");
setSize(100,100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
meuLabel = new JLabel();
meuLabel.setText("Esse é Meu Label");
add(meuLabel)
}
}
public class App {
public static void main(String[] args) {
MeuFrame meuFrame = new MeuFrame();
meuFrame.setVisible(true);
}
}

15 Stephenson Galvão
sgalvao@ifpi.edu.br
Exercício
● Utilizando herança, crie um label com seu
nome em um JFrame e exiba o Frame criado.

16 Stephenson Galvão
sgalvao@ifpi.edu.br
Opções de modularização
● Criação de um método só de inicialização

import javax.swing.JFrame; Essa área se preocupa em


import javax.swing.JLabel; criar os objetos do JFrame
public class MeuFrame extends JFrame {
private JLabel meuLabel;
public MeuFrame() {
meuLabel = new JLabel();
inicializacao();
}
private void inicializacao(){
setTitle("Titulo Frame");
setSize(100,100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
meuLabel.setText("Esse é Meu Label");
add(meuLabel); Aqui são colocados os comandos
} de configuração.
}

17 Stephenson Galvão
sgalvao@ifpi.edu.br
JTextField
● JTextField
– Um campo de texto que permite que o usuário
digite uma pequena quantidade de texto
Declarando um Instanciando um
JTextField JTextField

JTextField meuTextField = new JTextField();


meuTextField.setColumns(30);

Colocando o tamanho do
JtextField.

18 Stephenson Galvão
sgalvao@ifpi.edu.br
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Ola {
public static void main(String[] args) {
JFrame meuFrame = new JFrame("Meu Frame");
meuFrame.setVisible(true);
meuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
meuFrame.setSize(400, 200);
Adcionar o JTextField
JLabel meuLabel = new JLabel(); no JFrame
meuLabel.setText("Meu Primeiro Label");
JTextField meuTextField = new JTextField();
meuTextField.setColumns(30);
meuFrame.add(meuLabel);
meuFrame.add(meuTextField);
}
}

19 Stephenson Galvão
sgalvao@ifpi.edu.br
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Ola {
public static void main(String[] args) {
JFrame meuFrame = new JFrame("Meu Frame");
meuFrame.setVisible(true);
meuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
meuFrame.setSize(400, 200);
JLabel meuLabel = new JLabel();
meuLabel.setText("Meu Primeiro Label");
JTextField meuTextField = new JTextField();
meuTextField.setColumns(30);
meuFrame.add(meuLabel);
meuFrame.add(meuTextField);
}
}
20 Stephenson Galvão
sgalvao@ifpi.edu.br
Layout
● Layout (Gerenciador de Layout)
– Um objeto que determina o tamanho e a posição
dos componentes dentro de um container.
– Exemplos de Layout

21 Stephenson Galvão
sgalvao@ifpi.edu.br
Layout
● Layout
– BorderLayout
– BoxLayout
– CardLayout
– FlowLayout
– GridBagLayout
– GridLayout
– GroupLayout
– SpringLayout
● Mais em:

– http://docs.oracle.com/javase/tutorial/uiswing/layout/
visual.html 22 Stephenson Galvão
sgalvao@ifpi.edu.br
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Ola {
public static void main(String[] args) {
JFrame meuFrame = new JFrame("Meu Frame");
meuFrame.setVisible(true);
meuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
meuFrame.setSize(400, 200);
meuFrame.setLayout(new FlowLayout());
JLabel meuLabel = new JLabel();
meuLabel.setText("Meu Primeiro Label");
JTextField meuTextField = new JTextField();
meuTextField.setColumns(15);
meuFrame.add(meuLabel);
meuFrame.add(meuTextField); Informando o Layout
}
}

23 Stephenson Galvão
sgalvao@ifpi.edu.br
Exercício
● Utilizando herança crie um Frame com um
label com o texto “nome:” e uma caixa de
texto com 10 colunas. Depois exiba o frame
que possui os dois elementos.

24 Stephenson Galvão
sgalvao@ifpi.edu.br
Resposta

public class MeuFrame extends JFrame {


private JLabel nomeLabel;
private JTextField nomeTextField;
public MeuFrame() {
nomeLabel = new JLabel(); public class App {
nomeTextField = new JTextField(); public static void main(String[] args) {
inicializacao(); MeuFrame meuFrame = new MeuFrame();
} meuFrame.setVisible(true);
}
private void inicializacao(){ }
setTitle("Titulo Frame");
setSize(100,100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
nomeLabel.setText("Nome:");
nomeTextField.setColumns(10);
add(nomeLabel);
add(nomeTextField);
}
}

25 Stephenson Galvão
sgalvao@ifpi.edu.br
JButton
● Objeto que pode ser configurado e geralmente
significa ação.
Declarando um Instanciando um
JButton JButton

JButton meuButton = new JButton();


meuButton.setText("Butão");

Informando o texto do
botão.

26 Stephenson Galvão
sgalvao@ifpi.edu.br
...
public class Ola {
public static void main(String[] args) {
JFrame meuFrame = new JFrame("Meu Frame");
meuFrame.setVisible(true);
meuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
meuFrame.setSize(400, 200);
meuFrame.setLayout(new FlowLayout());
JLabel meuLabel = new JLabel();
meuLabel.setText("Meu Primeiro Label");
JTextField meuTextField = new JTextField();
meuTextField.setColumns(15);
JButton meuButton = new JButton();
meuButton.setText("Butão");
meuFrame.add(meuLabel);
meuFrame.add(meuTextField);
meuFrame.add(meuButton);
}
}

27 Stephenson Galvão
sgalvao@ifpi.edu.br
Exercício
● Com herança crie o seguinte Frame

28 Stephenson Galvão
sgalvao@ifpi.edu.br
Resposta
public class MeuFrame extends JFrame {
private JLabel nomeLabel;
private JTextField nomeTextField;
private JButton enviarButton;
public MeuFrame() {
nomeLabel = new JLabel(); public class App {
nomeTextField = new JTextField(); public static void main(String[] args) {
enviarButton = new JButton(); MeuFrame meuFrame = new MeuFrame();
inicializacao(); meuFrame.setVisible(true);
} }
}
private void inicializacao(){
setTitle("Titulo Frame");
setSize(100,100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
nomeLabel.setText("Nome:");
nomeTextField.setColumns(10);
enviarButton.setText("Enviar");
add(nomeLabel);
add(nomeTextField);
add(enviarButton);
}
}
29 Stephenson Galvão
sgalvao@ifpi.edu.br
Exercício de Classe
public class MeuFrame extends JFrame {
private JLabel nomeLabel;
● GridLayout
private JTextField nomeTextField;
private JButton enviarButton;
private JButton cancelarButton; – Divide a tela em
public MeuFrame() { linhas e colunas.
nomeLabel = new JLabel();
nomeTextField = new JTextField();
enviarButton = new JButton();
cancelarButton = new JButton();
inicializacao();
}
private void inicializacao(){
setTitle("Titulo Frame");
setSize(100,100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(2, 2));
nomeLabel.setText("Nome:");
nomeTextField.setColumns(10);
enviarButton.setText("Enviar");
cancelarButton.setText("Cancelar");
add(nomeLabel);
add(nomeTextField);
add(enviarButton); L:1 C:1 Colunas
add(cancelarButton); L:1 C:2
} Linhas
} L:2 C:1
30 Stephenson Galvão
L:2 C:2 sgalvao@ifpi.edu.br
Exercício
● Crie o seguinte Frame.

31 Stephenson Galvão
sgalvao@ifpi.edu.br
Eventos
● Eventos
– Indicam:
● Interação do usuário com a interface.
– Podem ser de vários tipos:
● Clicar em um botão.
● Digitar um texto.
● Escolher um item.
● Fechar um janela.
● Mover o mouse.
– Eventos podem levar à tarefas:
● Limpar uma caixa de texto.
● Ativar um popup.

32 Stephenson Galvão
sgalvao@ifpi.edu.br
Eventos
● Tratamento de eventos:
– Liga um evento à uma ação
● Funcionamento (simplificado).
– Cada objeto (JComponente) possui vários tipos de eventos.
– Esse eventos são manipulados por um handler (manipulado)
apropriado para o eventos.
– Para manipular evento o handler ser cadastrado no objeto que
deseja manipular.
<<interface>>
InterfaceHandler

MeuHandler
JComponent

Handler Cadastrados. 33 Stephenson Galvão


metodoAcao() sgalvao@ifpi.edu.br
Eventos
● Na Prática
– Criando o Handler

Implementa a interface de manipulação

public class Handler implements ActionListener{


public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Ola");
}
}

Interface contém um método que é acionado


quando o evento é executado.

34 Stephenson Galvão
sgalvao@ifpi.edu.br
Eventos
public class MeuJFrame extends JFrame{
● Na Prática JLabel meuLabel;
JTextField meuTextField;
JButton meuButton;
– Cadastrando o manipulador.
public MeuJFrame() {
super();
...
inicializacao();
}
public void inicializacao() {
setLayout(new FlowLayout());
setSize(400,200);
meuLabel.setText("Meu Primeiro Label");
meuTextField.setColumns(15);
meuButton.setText("Botão");
add(meuLabel);
add(meuTextField);
add(meuButton);
Handler meuHandler = new Handler();
meuButton.addActionListener(meuHandler);
}
}

35 Stephenson Galvão
sgalvao@ifpi.edu.br
Código Completo
public class MeuJFrame extends JFrame{
JLabel meuLabel;
JTextField meuTextField;
JButton meuButton;
public MeuJFrame() { public class Handler implements ActionListener{
super(); public void actionPerformed(ActionEvent e) {
... JOptionPane.showMessageDialog(null, "Ola");
inicializacao(); }
} }
public void inicializacao() {
setLayout(new FlowLayout());
setSize(400,200);
meuLabel.setText("Nomel");
meuTextField.setColumns(15);
meuButton.setText("Botão");
add(meuLabel);
add(meuTextField);
add(meuButton);
Handler meuHandler = new Handler();
meuButton.addActionListener(meuHandler);
}
}

36 Stephenson Galvão
sgalvao@ifpi.edu.br
Evento
public class MeuJFrame extends JFrame{
● Cada JComponent JLabel meuLabel;
JTextField meuTextField;
JButton meuButton;
– Possui seus eventos e public MeuJFrame() {
podem ter seus super();
manipuladores ...
inicializacao();
}
public void inicializacao() {
setLayout(new FlowLayout());
setSize(400,200);
meuLabel.setText("Nomel");
meuTextField.setColumns(15);
meuButton.setText("Botão");
add(meuLabel);
add(meuTextField);
add(meuButton);
Handler meuHandler = new Handler();
meuButton.addActionListener(meuHandler);
meuTextField.addActionListener(meuHandler);
}
Tratar evento }
no TextField
37 Stephenson Galvão
sgalvao@ifpi.edu.br
Evento
public class MeuJFrame extends JFrame{
JLabel meuLabel;
● Um evento de um JTextField meuTextField;
JButton meuButton;
componente public MeuJFrame() {
super();
– Poder ter vários ...
manipuladores }
inicializacao();

public void inicializacao() {


setLayout(new FlowLayout());
public class Handler1 implements ActionListener{ setSize(400,200);
public void actionPerformed(ActionEvent e) { meuLabel.setText("Nomel");
JOptionPane.showMessageDialog(null, "1"); meuTextField.setColumns(15);
} meuButton.setText("Botão");
} add(meuLabel);
add(meuTextField);
add(meuButton);
public class Handler2 implements ActionListener{ Handler1 meuHandler1 = new Handler1();
public void actionPerformed(ActionEvent e) { Handler2 meuHandler2 = new Handler2();
JOptionPane.showMessageDialog(null, "2"); meuButton.addActionListener(meuHandler1);
} meuButton.addActionListener(meuHandler2);
} }
}

38 Stephenson Galvão
sgalvao@ifpi.edu.br
Evento
● Event object
– Objeto enviado para o handler com informações
sobre o evento.

public class Handler1 implements ActionListener {


@Override
public void actionPerformed(ActionEvent e) {
JTextField textField = (JTextField) e.getSource();
JOptionPane.showMessageDialog(null,textField.getText());
}
}

39 Stephenson Galvão
sgalvao@ifpi.edu.br
Exemplo
public class MeuJFrame extends JFrame{
JLabel meuLabel;
JTextField meuTextField;
JButton meuButton;
public MeuJFrame() {
super(); public class Handler1 implements ActionListener {
... @Override
inicializacao(); public void actionPerformed(ActionEvent e) {
} JTextField textField = (JTextField) e.getSource();
JOptionPane.showMessageDialog(null,textField.getText());
public void inicializacao() { }
setLayout(new FlowLayout()); }
setSize(400,200);
meuLabel.setText("Nomel");
meuTextField.setColumns(15);
meuButton.setText("Botão");
add(meuLabel);
add(meuTextField);
add(meuButton);
Handler1 meuHandler = new Handler1();
meuButton.addActionListener(meuHandler);
meuTextField.addActionListener(meuHandler);
}
}

40 Stephenson Galvão
sgalvao@ifpi.edu.br
Evento
● Event source
– Componente GUI que o usuário interage.
● Event object
– Objeto que encapusula informações sobre o evento ocorrido.
● Event Listener
– Objeto que é notificado quando o evento ocorre.
– Alguns dos seus método são executados em resposta ao evento.

41 Stephenson Galvão
sgalvao@ifpi.edu.br
Eventos
● Existem vários tipos de eventos e vários tipos
de Listener.

42 Stephenson Galvão
sgalvao@ifpi.edu.br
KeyListener
● Definição
– Listener que recebe keyboard events.
– Possui 3 métodos:
● keyPressed: quando qualquer tecla é precionada.
● keyTyped: quando qualquer tecla que não seja ação
seja precionada.
● keyReleased:quando um tecla é liberada. Após
keyPressed ou keyTyped event.

43 Stephenson Galvão
sgalvao@ifpi.edu.br
Exemplo
public class MeuJFrame extends JFrame{
JLabel meuLabel;
JTextField meuTextField;
JButton meuButton;
public class KeyHandler implements KeyListener{
public MeuJFrame() {
super(); @Override
... public void keyPressed(KeyEvent e) {
inicializacao(); }
}
@Override
public void inicializacao() { public void keyTyped(KeyEvent e) {
setLayout(new FlowLayout()); }
setSize(400,200);
meuLabel.setText("Nomel"); @Override
meuTextField.setColumns(15); public void keyReleased(KeyEvent e) {
meuButton.setText("Botão"); char a =e.getKeyChar();
add(meuLabel); JOptionPane.showMessageDialog(null, "Liberada:"+a);
add(meuTextField); }
add(meuButton); }
KeyHandler kh = new KeyHandler();
meuTextField.addKeyListener(kh);
}
}

44 Stephenson Galvão
sgalvao@ifpi.edu.br
Exercício
● Crie a interface abaixo e:
● ao ser acionado o botão ok, deve-se exibir um pop-up
dizendo “botão ok”,
● ao ser acionado o “botão cancelar” deve exibir um pop-
up dizendo “botão cancelar”.
● Ao ser liberada uma tecla dentro do campo nome deve
exibir um pop-up com a tecla liberada.
● Ao ser liberada uma tecla dentro do campo idade deve
exibir um pop-up com a tecla liberada.

45 Stephenson Galvão
sgalvao@ifpi.edu.br
Slides Antigos

46 Stephenson Galvão
sgalvao@ifpi.edu.br
Código Completo
public class MeuJFrame extends JFrame{
JLabel meuLabel;
JTextField meuTextField;
JButton meuButton;
public MeuJFrame() { public class Handler implements ActionListener{
super(); public void actionPerformed(ActionEvent e) {
... JOptionPane.showMessageDialog(null, "Ola");
inicializacao(); }
} }
public void inicializacao() {
setLayout(new FlowLayout()); ● Problema:
setSize(400,200);
meuLabel.setText("Nomel"); – Não podemos manipular os
meuTextField.setColumns(15);
meuButton.setText("Botão"); objetos do Frame dentro do
add(meuLabel); método que realiza a ação.
add(meuTextField);
add(meuButton); ● Exemplo: exibir o texto do
Handler meuHandler = new Handler(); componente meuTextField
meuButton.addActionListener(meuHandler); no lugar da mensagem Ola.
}
}

47 Stephenson Galvão
sgalvao@ifpi.edu.br
Solução
public class MeuJFrame extends JFrame{ ● Classe Aninhada:
JLabel meuLabel;
JTextField meuTextField; – É uma classe declarada
JButton meuButton; dentro de outra classe.
Colocar a declaração do
public MeuJFrame() { Handler dentro do Frame – Ela funciona como uma
... classe privada que pode
inicializacao(); ser utilizada apenas pela
} classe que à abriga.
public void inicializacao() { – Os elementos não
setLayout(new FlowLayout()); privados da classe mais
setSize(400,200);
meuLabel.setText("Nomel"); externa são acessíveis à
meuTextField.setColumns(15); classe mais interna.
meuButton.setText("Botão");
add(meuLabel); – Exemplo:
add(meuTextField); ● meuLabel, meuTextField
add(meuButton); e meuButton podem ser
Handler meuHandler = new Handler(); acessados dentro da
meuButton.addActionListener(meuHandler); classe Handler.
}
public class Handler implements ActionListener{
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Ola");
}
}
}

48 Stephenson Galvão
sgalvao@ifpi.edu.br
Exemplo
public class MeuJFrame extends JFrame{
JLabel meuLabel;
JTextField meuTextField;
JButton meuButton;
Texto do elemento meuTextField
public MeuJFrame() { é acessado dentro do método
... actionPerformed da classe Handler.
inicializacao();
}
public void inicializacao() {
setLayout(new FlowLayout());
setSize(400,200);
meuLabel.setText("Nome");
meuTextField.setColumns(15);
meuButton.setText("Botão");
add(meuLabel);
add(meuTextField);
add(meuButton);
Handler meuHandler = new Handler();
meuButton.addActionListener(meuHandler);
}
public class Handler implements ActionListener{
public void actionPerformed(ActionEvent e) {
String t = meuTextField.getText();
JOptionPane.showMessageDialog(null,t);
}
}
}

49 Stephenson Galvão
sgalvao@ifpi.edu.br
Exercício 1
● Crie a interface abaixo e, ao ser acionado o
botão ok, deve-se exibir um pop-up com o
nome e a idade digitados na caixa de texto.

50 Stephenson Galvão
sgalvao@ifpi.edu.br
Exercício 2
● Crie a interface abaixo.
● O botão ok exibe um pop-up com o nome e a
idade digitados na caixa de texto.
● O botão Cancelar limpa os campos de texto.
– Dica: crie outro handler para o botão cancelar que
realize a ação desejada

51 Stephenson Galvão
sgalvao@ifpi.edu.br
Parâmetro Event
public class MeuJFrame extends JFrame{
JLabel nomeLabel;
JLabel idadeLabel; Observe o mesmo hardler
JTextField nomeField;
JTextField idadeField;
sendo cadastrado para 2
JButton okButton; eventos.
JButton cancelarButton;
public MeuJFrame() {
...
inicializacao();
}
public void inicializacao() {
...
Handler meuHandler = new Handler();
okButton.addActionListener(meuHandler);
cancelarButton.addActionListener(meuHandler);
}
public class Handler implements ActionListener{
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, “Olá”);
}
} O que ocorre neste caso?
}

52 Stephenson Galvão
sgalvao@ifpi.edu.br
Parâmetro Event
public class MeuJFrame extends JFrame{
JLabel nomeLabel;
JLabel idadeLabel; Evento é passado como parâmetro
JTextField nomeField; para o método de ação
JTextField idadeField;
JButton okButton;
JButton cancelarButton;
public MeuJFrame() {
...
inicializacao();
}
public void inicializacao() { Um evento possui
... vários atributos,
Handler meuHandler = new Handler(); inclusive a fonte de
okButton.addActionListener(meuHandler); onde foi gerado
cancelarButton.addActionListener(meuHandler);
}
public class Handler implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource()==okButton)
JOptionPane.showMessageDialog(null, "Ok");
if(e.getSource()==cancelarButton)
JOptionPane.showMessageDialog(null, "Canclar");
}
}
}

53 Stephenson Galvão
sgalvao@ifpi.edu.br
Exercício 3
● Crie a interface abaixo.
● O botão ok exibe um pop-up com o nome e a
idade digitados na caixa de texto.
● O botão Cancelar limpa os campos de texto.
– Dica: crie somente um handler que verifique a
fonte que disparou o evento.

54 Stephenson Galvão
sgalvao@ifpi.edu.br
Lista de Eventos

55 Stephenson Galvão
sgalvao@ifpi.edu.br
Lista de Handler(Event Listener)

56 Stephenson Galvão
sgalvao@ifpi.edu.br
Observações
● O ActionEvent não é privativo do JButon o
JTextField também dispara o mesmo evento
quando a tecla entre e precisada dentro da
caixa de texto.
– Exemplo no slide a seguir

57 Stephenson Galvão
sgalvao@ifpi.edu.br
public class MeuJFrame extends JFrame{
JLabel nomeLabel;
JLabel idadeLabel;
JTextField nomeField;
JTextField idadeField;
JButton okButton;
JButton cancelarButton;
public MeuJFrame() {
...
inicializacao();
}
public void inicializacao() {
...
Handler meuHandler = new Handler();
okButton.addActionListener(meuHandler);
cancelarButton.addActionListener(meuHandler);
nomeField.addActionListener(meuHandler);
}
public class Handler implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource()==okButton)
JOptionPane.showMessageDialog(null, "Ok");
if(e.getSource()==cancelarButton)
JOptionPane.showMessageDialog(null, "Canclar");
if(e.getSource()==nomeField)
JOptionPane.showMessageDialog(null, "Caixa de nome");
}
}
}

58 Stephenson Galvão
sgalvao@ifpi.edu.br
Exercício 3
● Crie a interface abaixo.
● O botão ok exibe um pop-up com o nome e a
idade digitados na caixa de texto.
● O botão Cancelar limpa os campos de texto.
● Ao aperta a tecla entre da caixa de texto do
nome, é exibido um pop-up com o nome.
● Ao aperta a tecla entre da caixa de texto da
idade, é exibido um pop-up com a idade
digitada.

59 Stephenson Galvão
sgalvao@ifpi.edu.br
Tarefa
● Leitura dos item 14.5 ate 14.9 do livro texto e
fazer os exemplo contidos nele.
● Fazer o robô.

60 Stephenson Galvão
sgalvao@ifpi.edu.br

Vous aimerez peut-être aussi