|
Intercettazione tasti
> Esempio di inputMap-actionmap > in depth
|
|
Esempio di inputMap-actionmap
|
package it.unitn.prog2.keybindingdemo;
import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import javax.swing.*; /* Usare il tab per fare ciclare il focus tra le componenti */ public class KeyBindingDemo {
/** * @param args the command line arguments */ public static void main(String[] args) { new KeyBindingDemo(); }
KeyBindingDemo() { JFrame f = new JFrame(); f.setSize(400, 400); JPanel p = (JPanel) (f.getContentPane()); p.setLayout(new BorderLayout()); //==================================== AbstractAction enterAction = new AbstractAction() { public void actionPerformed(ActionEvent tf) { System.out.println("The Enter key has been pressed in "+tf.getSource().getClass().toString());
} }; //==================================== AbstractAction enterAction2 = new AbstractAction() { public void actionPerformed(ActionEvent tf) { System.out.println("The Enter key has been pressed on the yellow panel ");
} }; p.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "doEnterAction"); p.getActionMap().put("doEnterAction", enterAction); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b=new JButton(); b.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "doEnterAction"); b.getActionMap().put("doEnterAction", enterAction); p.add(b,BorderLayout.NORTH); //-------------------- JPanel ip=new JPanel(); ip.setBackground(Color.yellow); ip.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "doEnterAction"); ip.getActionMap().put("doEnterAction", enterAction2); p.add(ip,BorderLayout.CENTER); //-------------------- JTextField tf=new JTextField(); p.add(tf,BorderLayout.SOUTH); tf.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "doEnterAction"); tf.getActionMap().put("doEnterAction", enterAction); f.setVisible(true); } }
|
|
|