How to include in my class an event that gives me the ability to click on JButton
and it shows a JOptionPane
? And, in the same way, in the same JButton
, I press the ENTER and it shows me the same JOptionPane
?
How to include in my class an event that gives me the ability to click on JButton
and it shows a JOptionPane
? And, in the same way, in the same JButton
, I press the ENTER and it shows me the same JOptionPane
?
Click events can be captured via a ActionListener
. Pressing a particular key can be done with KeyEventDispatcher
together at KeyboardFocusManager
.
This response from utluiz explains why it is better to use KeyboardFocusManager
instead of adding a KeyListener
for your button. Although both are for capturing keyboard events, KeyListener
does not work if the focus is on another component.
A simple example that displays a JOptionPane
when the ENTER key is pressed or when the click event occurs in JButton
:
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class MeuJFrame extends JFrame {
public MeuJFrame() {
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JButton btn = new JButton("Mostrar JOptionPane");
getContentPane().add(btn);
// Quando clicado
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
mostrarJOptionPane();
}
});
// Quando uma tecla for pressionada (Nesse exemplo escolhi a tecla 'B').
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventDispatcher(new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if(event.getID() == KeyEvent.KEY_RELEASED
&& event.getKeyCode() == KeyEvent.VK_ENTER){
mostrarJOptionPane();
return true;
}
return false;
}
});
}
private void mostrarJOptionPane(){
JOptionPane.showMessageDialog(null, "Hello World.");
}
public static void main(String[] args) {
new MeuJFrame().setVisible(true);
}
}
As KeyboardFocusManager
captures all events, you must do a constraint to do something only when a key is pressed and released ( KeyEvent#KEY_RELEASED
), so this excerpt:
if(event.getID() == KeyEvent.KEY_RELEASED ...
Otherwise, an action will be triggered (in this case, show JOptionPane
) for each captured event: KeyEvent#KEY_RELEASED
, KeyEvent#KEY_PRESSED
and KeyEvent#KEY_TYPED
.
I took the 'Enter' click on a textfield in javafx like this:
private void clikBusc(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
System.out.println("deu certo");
}
}
So, whenever I click on the enter within the textField, it will go into the if, and execute whatever is put in!