Acho que acertei como usar os métodos “getInputMap()” e “getActionMap()” que a documentação recomenda. O exemplo abaixo funcionou para as teclas F1 e F2, F1 com esses dois métodos recomendados e F2 com o antigo.
/*
* Created on 24/02/2004
*/
package br.pro.douglas.teste;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
/**
* @author Douglas Siviotti
*/
public class JFrameCaptureKeys extends JFrame implements ActionListener {
public static void main(String[] args) {
JFrameCaptureKeys app = new JFrameCaptureKeys();
app.setVisible(true);
}
private final String commandF1 = "F1";
private final String commandF2 = "F2";
private javax.swing.JPanel jContentPane = null;
private javax.swing.JTextField jTextField = null;
private Action pressF1;
/**
* This is the default constructor
*/
public JFrameCaptureKeys() {
super();
/* Cria uma Action para quando pressionar F1 */
pressF1 = new AbstractAction(commandF1){
public void actionPerformed(ActionEvent e) {
System.out.println("F1 pressionado");
}
};
/* Guarda a condição - sem isso não funciona */
int cond = JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT;
/* Cria KeyStrokes para F1 e F2 */
KeyStroke f1 = KeyStroke.getKeyStroke(KeyEvent.VK_F1,0);
KeyStroke f2 = KeyStroke.getKeyStroke(KeyEvent.VK_F2,0);
/* Guarda o RootPane */
JRootPane rootPane = getRootPane();
/* Modo obsoleto */
rootPane.registerKeyboardAction(this, commandF2, f2, cond);
/* Modo recomendado */
rootPane.getInputMap(cond).put(f1, commandF1);
rootPane.getActionMap().put(commandF1, pressF1 );
/* Inicialização da JFrame */
initialize();
}
public void actionPerformed(ActionEvent e) {
String key = e.getActionCommand();
if (key.equals(commandF2))
System.out.println("F2");
}
/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private javax.swing.JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new javax.swing.JPanel();
jContentPane.setLayout(new java.awt.BorderLayout());
jContentPane.add(getJTextField(), java.awt.BorderLayout.SOUTH);
}
return jContentPane;
}
/**
* This method initializes jTextField
*
* @return javax.swing.JTextField
*/
private javax.swing.JTextField getJTextField() {
if(jTextField == null) {
jTextField = new javax.swing.JTextField();
}
return jTextField;
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.pack();
this.setSize(400, 300);
this.setContentPane(getJContentPane());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}