/*
Este exemplo mostra como fazer com que um JButton
reaja ao pressionamento da tecla Enter.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Estudos extends JFrame{
public Estudos() {
super("A classe JButton");
Container c = getContentPane();
c.setLayout(new FlowLayout(FlowLayout.LEFT));
// Cria um botão com o texto "Clique Aqui"
JButton btn = new JButton("Clique Aqui");
btn.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null,
"Fui clicado");
}
}
);
// Faz com que o botão "reaja" ao pressionar Enter
reagirEnter(btn);
// Adiciona o botão à janela
c.add(btn);
setSize(350, 250);
setVisible(true);
}
public static void reagirEnter(JButton btn){
btn.registerKeyboardAction(
btn.getActionForKeyStroke(
KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false)),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false),
JComponent.WHEN_FOCUSED
);
btn.registerKeyboardAction(
btn.getActionForKeyStroke(
KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true)),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true),
JComponent.WHEN_FOCUSED
);
}
public static void main(String args[]){
Estudos app = new Estudos();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}