Search code examples
javaswingnetbeans-6.9key-bindingskey-events

Why do key bindings die?


This application needs to send a motor move command when a GUI button or an arrow key is pressed and a motor stop command when the GUI button or an arrow key is released. These bindings work fine for the down arrow until the corresponding GUI button is pressed. After the GUI button is pressed the arrow key is ignored. If it is the focus change that killed the binding, how can bindings be programmed to be independent of focus chages? If not, what is the real problem and how is it repaired?

Key Bindings

Action tiltStop = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
        MotorStop(TILT_AXIS);
    }
};
mainPanel.getInputMap().put(KeyStroke
    .getKeyStroke(KeyEvent.VK_DOWN, 0, true), "tiltStop");
mainPanel.getActionMap().put("tiltStop", tiltStop);
Action tiltDown = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
        MotorMove(TILT_AXIS, NEGATIVE_DIR);
    }
};
mainPanel.getInputMap().put(KeyStroke
    .getKeyStroke(KeyEvent.VK_DOWN, 0, false), "tiltDown");
mainPanel.getActionMap().put("tiltDown", tiltDown);

GUI buttons

private void jButtonAxisDownMousePressed(java.awt.event.MouseEvent evt) {
    MotorMove(TILT_AXIS, NEGATIVE_DIR);
}                                              
private void jButtonAxisDownMouseReleased(java.awt.event.MouseEvent evt) {
    MotorStop(TILT_AXIS);
}                                               

Solution

  • how can bindings be programmed to be independent of focus chages?

    Look at the getInputMap() method. There are 3 different InputMaps. You want the one that is an ancestor so it will work even when the component doesn't have focus.