سؤال

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);
}                                               
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

I have an idea of the problem, but not entirely sure.

When you press down on the mouse button, it starts working with the mouse. When you release the button, it's still working the mouse and it's always released at that point, and always doing the function for the mouse release. Therefore when it does the key command that makes it move, the mouserelease function is undoing the movements - making it 0.

Add in a boolean called mousedown that gets set to true when it's pressed, and set to false at the end of the release function. Set it so it only calls to the release function when the mousedown boolean is true.

try getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put... instead of getInputMap().put... . This change worked for me, and one of these added in the rootPane works wherever the focus is.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top