1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DemoButtonKeyBinding {
public static void main(String[] args) {
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(100, 30, 100, 30));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets=new Insets(0,5,0,0);
frame.add(panel);
JLabel label = new JLabel("Saisir un truc :");
panel.add(label,gbc);
JTextField field = new JTextField(10);
panel.add(field,gbc);
JButton button = new JButton("Cliquez-moi !");
button.addActionListener(e->JOptionPane.showMessageDialog(panel, "Vous avez saisi : \""+field.getText()+"\""));
panel.add(button,gbc);
// keybinding
InputMap inputMap = button.getInputMap(JComponent.WHEN_FOCUSED); // récupère les key bindings lorsque le bouton a le focus
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,false),"pressed"); // dit que lorsqu'on appuie sur la touche espace, on déclenche l'action d'id pressed
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,true),"released"); // dit que lordqu'on appuie sur la touche return, on déclenche l'action released
// actionbinding
ActionMap actionMap = button.getActionMap();
actionMap.put("released",new AbstractAction() { // associe à l'action d'id released le fait qu'on clique sur le bouton
@Override
public void actionPerformed(ActionEvent e) {
button.doClick(); // on clique le bouton
}
});
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
} |
Partager