Java/Swing/Eventos e Action listeners: diferenças entre revisões

[edição não verificada][edição não verificada]
Conteúdo apagado Conteúdo adicionado
Albmont (discussão | contribs)
m mais um avanço milimétrico, ainda sem código fonte
 
Albmont (discussão | contribs)
Mostrando um fracasso instrutivo
Linha 1:
A comunicação entre os diversos ''widgets'' é feita através de '''eventos''' (''events'', em inglês) e de '''action listeners'''. Os conceitos estão explicados no livro [[Programação em GUI]], capítulo [[Programação em GUI/Eventos, sinais, slots e callbacks|Eventos, sinais, slots e callbacks]].
 
== Primeira tentativa ==
O objetivo é criar um programa que mostre um botão (com a ''string'' OK) e uma caixa de texto. Ao clicar-se no botão, a caixa de texto responde, apresentando a ''string'' OK.
 
Para começar, vamos escrever o esqueleto do programa:
 
<source lang="java">
// inicio do programa swing_button_1 - versao 0.0
 
import javax.swing.*; //All swing components live
//in the javax.swing package
 
import java.awt.*;
import java.awt.event.*;
 
// many widgets under a box
public class swing_button_1 {
public static void main(String[] args) {
 
// creates the Frame
JFrame frame = new JFrame("swing_button_1");
 
// defines frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// creates the (vertical) box
Box vbox = new Box(BoxLayout.Y_AXIS);
 
// places the box inside the frame
frame.add(vbox);
// creates the elements of the vbox
// creates the button
JButton button1 = new JButton("OK");
JTextField entry1 = new JTextField("");
 
// add button and textfield inside the vbox
vbox.add(button1);
vbox.add(entry1);
 
// set frame to a decent size (default is a small frame)
frame.setSize(212, 258);
// makes frame (and everything in it) visible
frame.setVisible(true);
}
}
// fim do programa swing_button_1 - versao 0
</source>
 
O programa acima não faz nada: pode-se clicar no botão, mas isto não tem efeitos. Precisamos incluir dois elementos:
* o botão ''button1'' deve incluir um ''actionListener'', para que o clicar nele tenha algum efeito
* a caixa de texto ''entry1'' deve incluir um ''actionPerformed'', para que ela reaja ao clicar do botão
 
Incluir um ''actionListener'' no botão é muito simples: basta chamar o membro ''addActionListener'', passando como argumento um objeto do tipo ''ActionListener'':
<source lang="java">
button1.addActionListener(al);
</source>
 
Já a criação do ''actionListener'' é mais complicada. Um ''actionListener'' deve ter um membro ''actionPerformed''; assim, poderíamos ter:
<source lang="java">
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("OK");
}
};
</source>
 
A versão preliminar do código, que ainda não faz aparecer "OK" na caixa de texto, mas faz aparecer "OK" na console, é:
 
<source lang="java">
// inicio do programa swing_button_1 - versao 0.1
 
import javax.swing.*; //All swing components live
//in the javax.swing package
 
import java.awt.*;
import java.awt.event.*;
 
// many widgets under a box
public class swing_button_1 {
public static void main(String[] args) {
 
// creates the Frame
JFrame frame = new JFrame("swing_button_1");
 
// defines frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// creates the (vertical) box
Box vbox = new Box(BoxLayout.Y_AXIS);
 
// places the box inside the frame
frame.add(vbox);
// creates the elements of the vbox
// creates the button
JButton button1 = new JButton("OK");
JTextField entry1 = new JTextField("");
 
// ActionListener: makes button1 iteract with the System
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("OK");
}
};
// add ActionListener to the button
button1.addActionListener(al);
 
// add button and textfield inside the vbox
vbox.add(button1);
vbox.add(entry1);
 
// set frame to a decent size (default is a small frame)
frame.setSize(212, 258);
// makes frame (and everything in it) visible
frame.setVisible(true);
}
}
// fim do programa swing_button_1 - versao 0.1
</source>
E aqui a coisa se complica: não dá para simplesmente trocar a variável ''al'' para:
 
<source lang="java">
// ActionListener: makes button1 iteract with entry1
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
entry1.setText("OK");
}
};
</source>
porque o compilador dá erro, com uma mensagem incompreensível (''Cannot refer to a non-final variable entry1 inside an inner class defined in a different method'').
 
 
== Ligações externas ==