Capturar teclas en Swing/ Keys Capture in Swing


Para capturar las combinaciones de teclas dentro de una aplicación swing, se deben de utilizar dos objetos (ActionMap e InputMap ).

1. Creamos nuestro Mapa de accion.
ActionMap mapaAccion = jPanel1.getActionMap();
2. Indicamos el componente donde queremos que trabaje el mapa.
InputMap map = jPanel1.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
3. Seleccionamos la combinación de teclas.
//F1
KeyStroke key_F1 = KeyStroke.getKeyStroke(KeyEvent.VK_F1,0);

// CTRL + O
KeyStroke ctrl_O = KeyStroke.getKeyStroke(KeyEvent.VK_O,Event.CTRL_MASK);

// CTRL + C, CTRL + V
KeyStroke ctrl_C = KeyStroke.getKeyStroke(KeyEvent.VK_C,Event.CTRL_MASK, true);
KeyStroke ctrl_V = KeyStroke.getKeyStroke(KeyEvent.VK_V,Event.CTRL_MASK, true);

4. Indicamos y agregamos la acción a ejecutar.
//Key Actions
map.put(key_F1, "accion_F1");
mapaAccion.put("accion_F1",Accion_F1());


public AbstractAction Accion_F1(){
return new AbstractAction() { public void actionPerformed(ActionEvent e) { imprimir("F1"); } };
}


public void imprimir(String cadena){
System.out.println("Accion :"+ cadena);
jTextField1.setText(cadena);
}

Aqui el ejemplo:

// ACCIONES
public void mapeoTeclas(){

ActionMap mapaAccion = jPanel1.getActionMap();
InputMap map = jPanel1.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

//F1
KeyStroke key_F1 = KeyStroke.getKeyStroke(KeyEvent.VK_F1,0);

// CTRL + O
KeyStroke ctrl_O = KeyStroke.getKeyStroke(KeyEvent.VK_O,Event.CTRL_MASK);

// CTRL + C, CTRL + V
KeyStroke ctrl_C = KeyStroke.getKeyStroke(KeyEvent.VK_C,Event.CTRL_MASK, true);
KeyStroke ctrl_V = KeyStroke.getKeyStroke(KeyEvent.VK_V,Event.CTRL_MASK, true);

//Key Actions
map.put(key_F1, "accion_F1");
mapaAccion.put("accion_F1",Accion_F1());

map.put(ctrl_O , "accion_ctrl_o");
mapaAccion.put("accion_ctrl_o",Accion_CTRLO());

map.put(ctrl_C , "accion_ctrl_C");
mapaAccion.put("accion_ctrl_C",Accion_CTRLC());

map.put(ctrl_V , "accion_ctrl_V");
mapaAccion.put("accion_ctrl_V",Accion_CTRLV());
}

public AbstractAction Accion_CTRLO(){
return new AbstractAction() { public void actionPerformed(ActionEvent e) { imprimir("CTRL + O"); } };
}

public AbstractAction Accion_CTRLC(){
return new AbstractAction() { public void actionPerformed(ActionEvent e) { imprimir("CTRL + C"); } };
}

public AbstractAction Accion_CTRLV(){
return new AbstractAction() { public void actionPerformed(ActionEvent e) { imprimir("CTRL + V"); } };
}

public AbstractAction Accion_F1(){
return new AbstractAction() { public void actionPerformed(ActionEvent e) { imprimir("F1"); } };
}

public void imprimir(String cadena){
System.out.println("Accion :"+ cadena);
jTextField1.setText(cadena);
}

Solo hay que ejecutar el metodo mapeoTeclas() en el constructor de la clase.

Agrego el codigo fuente:
Source

Saludos

Posted in Etiquetas: , |