Java Reference
In-Depth Information
You can share actions between components by sharing ActionMap instances. The example
in Listing 2-10 creates four buttons, each with a different keystroke registered to it and possibly
a different focus-activation condition, as listed in Table 2-4. The button label signifies the
keystroke-activation conditions. The Action simply prints out a message and the activating
button label.
Listing 2-10. KeyStroke Listening
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class KeyStrokeSample {
private static final String ACTION_KEY = "theAction";
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("KeyStroke Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton buttonA =
new JButton("<html><center>FOCUSED<br>control alt 7");
JButton buttonB =
new JButton("<html><center>FOCUS/RELEASE<br>VK_ENTER");
JButton buttonC =
new JButton("<html><center>ANCESTOR<br>VK_F4+SHIFT_MASK");
JButton buttonD =
new JButton("<html><center>WINDOW<br>' '");
// Define ActionListener
Action actionListener = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
JButton source = (JButton)actionEvent.getSource();
System.out.println("Activated: " + source.getText());
}
};
KeyStroke controlAlt7 = KeyStroke.getKeyStroke("control alt 7");
InputMap inputMap = buttonA.getInputMap();
inputMap.put(controlAlt7, ACTION_KEY);
ActionMap actionMap = buttonA.getActionMap();
actionMap.put(ACTION_KEY, actionListener);
KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true);
inputMap = buttonB.getInputMap();
inputMap.put(enter, ACTION_KEY);
buttonB.setActionMap(actionMap);
Search WWH ::




Custom Search