Olá
Escrevi uma classe para teste de eventos. Ela consiste em um botão que chama outro botão etc e um contador que é incrementado a partir de um keyListener associado à tecla F12.
Mas o contador não funciona. Alguém sabe por que?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Teste extends JFrame {
private JPanel c;
private JButton
btn1,
btn2,
btn3;
private JLabel label;
private int counter;
public Teste() {
c = new JPanel();
c.setBackground(Color.WHITE);
label = new JLabel(String.valueOf(counter));
btn1 = new JButton("Primeiro clique");
btn1.setPreferredSize(new Dimension(120, 80));
btn2 = new JButton("Segundo clique");
btn2.setPreferredSize(new Dimension(120, 80));
btn3 = new JButton("Terceiro clique");
btn3.setPreferredSize(new Dimension(120, 80));
c.add(btn1, BorderLayout.CENTER);
ActionListener l1 = new ActionListener() {
public void actionPerformed(ActionEvent e) {
c.remove(btn1);
c.add(btn2);
c.repaint();
c.validate();
}
};
btn1.addActionListener(l1);
ActionListener l2 = new ActionListener() {
public void actionPerformed(ActionEvent e) {
c.remove(btn2);
c.add(btn3);
c.repaint();
c.validate();
}
};
btn2.addActionListener(l2);
ActionListener l3 = new ActionListener() {
public void actionPerformed(ActionEvent e) {
c.remove(btn3);
c.add(btn1);
c.repaint();
c.validate();
}
};
btn3.addActionListener(l3);
getContentPane().add(c, BorderLayout.CENTER);
getContentPane().add(label, BorderLayout.SOUTH);
//ao se apertar a tecla F12 o contador deverá incrementar
this.addKeyListener(
new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_F12) {
label.setText(String.valueOf(counter++));
c.repaint();
}
}
}
);
setVisible(true);
setLocationRelativeTo(null);
setSize(new Dimension(140,140));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Teste();
}
}
Obrigado a todos