Tengo un JFrame
con tres JButtons en él. Configuré txtSearch
(un componente JTextField
) para enfocar cuando se carga JFrame
. Uno de los botones está configurado como el botón predeterminado. Este es mi código:El botón predeterminado en JFrame no se activa cuando se presiona la tecla enter
private void formWindowOpened(java.awt.event.WindowEvent evt)
{
// btnRefresh.setMnemonic(KeyEvent.VK_R); // Even if this line
// is not commented, but
// still the event wouldn't fire.
this.getRootPane().setDefaultButton(btnRefresh);
}
Cuando se carga, el botón se acaba de seleccionar, pero no hizo nada cuando el Introduzca clave estaba siendo presionado. ¿Cómo lo implemento correctamente?
btnRefresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRefreshActionPerformed(evt);
}
});
private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(this, "Pressed!");
// Other codes here (Replace by JOptionPane)
}
Descubrí que la manera más fácil es llamar a requestFocusInWindow() DESPUÉS de que JFrame esté visible para establecer un botón predeterminado. Espero que esto ayude a alguien. – GeriBoss