I use the code below to detect when a key is being pressed. Unfortunately it
only responds when the key is first pressed.
What I would like to do is detect when the key is initially pressed, and
when it is released.
How do I modify the code below to achieve this?
Thanks.
=============================
//below is in main application view constructor
contentPane.getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(javax.swing.KeyStroke.getKeyStroke('a'),"a_pressed");
contentPane.getActionMap().put("a_pressed", new AbstractActionGB(gb));
//below is inner class in main application view
class AbstractActionGB extends javax.swing.AbstractAction {
model.GameBoard gb;
public AbstractActionGB(GameBoard gb) {
this.gb = gb;
}
public void actionPerformed(ActionEvent e)
{
System.out.println("A WAS PRESSED!!!");
gb.flipFlipper();
}
}
Rhino - 28 Feb 2006 18:02 GMT
>I use the code below to detect when a key is being pressed. Unfortunately
>it only responds when the key is first pressed.
[quoted text clipped - 29 lines]
> }
> }
See http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html.
--
Rhino
Vova Reznik - 28 Feb 2006 18:28 GMT
Yo may use method I wrote several years ago:
How to call:
registerKeyboardAction(c, actionForKeyRelease, KeyEvent.VK_A,
0, JComponent.WHEN_IN_FOCUSED_WINDOW, true);
registerKeyboardAction(c, actionForKeyPress, KeyEvent.VK_A,
0, JComponent.WHEN_IN_FOCUSED_WINDOW, false);
/**
* @param component
* @param action @see javax.swing.Action
* @param keyCode @see java.awt.event.KeyEvent
* @param modifier @see java.awt.event.InputEvent
* CTRL_MASK for example or 0 if no modifiers
* @param focusModifier @see JComponent
* @param onKeyRelease
* @throws IllegalArgumentException
*/
public static void registerKeyboardAction(JComponent component,
Action action, int keyCode, int modifier,
int focusModifier, boolean onKeyRelease) throws
IllegalArgumentException {
InputMap inputMap = component.getInputMap(focusModifier);
ActionMap actionMap = component.getActionMap();
if (actionMap == null) {
actionMap = new ActionMap();
component.setActionMap(actionMap);
}
inputMap.put(KeyStroke.getKeyStroke(keyCode, modifier, onKeyRelease),
action);
actionMap.put(action, action);
}
> I use the code below to detect when a key is being pressed. Unfortunately it
> only responds when the key is first pressed.
[quoted text clipped - 29 lines]
> }
> }
Andrey Kuznetsov - 28 Feb 2006 19:27 GMT
>I use the code below to detect when a key is being pressed. Unfortunately
>it only responds when the key is first pressed.
[quoted text clipped - 3 lines]
>
> How do I modify the code below to achieve this?
use need KeyStroke.getKeyStroke(int keyCode, int modifiers, boolean
onKeyRelease)

Signature
Andrey Kuznetsov
http://uio.imagero.com Unified I/O for Java
http://reader.imagero.com Java image reader
http://jgui.imagero.com Java GUI components and utilities