Java Reference
In-Depth Information
KeyStroke shiftF4 =
KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.SHIFT_MASK);
inputMap =
buttonC.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
inputMap.put(shiftF4, ACTION_KEY);
buttonC.setActionMap(actionMap);
KeyStroke space = KeyStroke.getKeyStroke(' ');
inputMap = buttonD.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(space, ACTION_KEY);
buttonD.setActionMap(actionMap);
frame.setLayout(new GridLayout(2,2));
frame.add(buttonA);
frame.add(buttonB);
frame.add(buttonC);
frame.add(buttonD);
frame.setSize(400, 200);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
Tip For text components, you can get the Keymap and bind an Action to a KeyStroke in one step with
addActionForKeyStroke(KeyStroke, Action) .
Figure 2-7 shows what the running program looks like.
Figure 2-7. KeyStroke listening example
 
Search WWH ::




Custom Search