1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
package bjc.utils.gui;
import java.awt.event.ActionEvent;
import java.util.function.Consumer;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.KeyStroke;
/**
* Simple {@link JButton} that provides an easy way to add a key-map to it.
*
* @author Ben Culkin
*
*/
public class SimpleKeyedButton extends JButton {
private final class KeyedButtonAction extends AbstractAction {
private static final long serialVersionUID = 5854121457339741391L;
private final Consumer<ActionEvent> aevListener;
private KeyedButtonAction(String name, Consumer<ActionEvent> aevListener) {
super(name);
this.aevListener = aevListener;
}
@Override
public void actionPerformed(ActionEvent aev) {
aevListener.accept(aev);
}
}
private static final long serialVersionUID = -8550504153221678178L;
private String label;
/**
* Create a new keyed button.
*
* @param label
* The label for the button.
*/
public SimpleKeyedButton(String label) {
super(label);
this.label = label;
}
/**
* Sets the default action for this button, and installs a global
* (WHEN_IN_FOCUSED_WINDOW) keystroke handler for it.
*
* @param eventName
* An unique internal name for the event.
* @param keystroke
* The keystroke for this event, passed to
* {@link KeyStroke#getKeyStroke(String)}.
* @param aevListener
* The listener that handles the implementation of the
* action.
* @return The action that was bound to the button.
*/
public Action setGlobalDefaultKeystroke(String eventName, String keystroke,
Consumer<ActionEvent> aevListener) {
Action act = new KeyedButtonAction(eventName, aevListener);
KeyStroke stroke = KeyStroke.getKeyStroke(keystroke);
this.setAction(act);
this.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(stroke, eventName);
this.getActionMap().put(eventName, act);
this.setText(label);
return act;
}
/**
* Installs a global (WHEN_IN_FOCUSED_WINDOW) keystroke handler for an action.
*
* @param eventName
* An unique internal name for the event.
* @param keystroke
* The keystroke for this event, passed to
* {@link KeyStroke#getKeyStroke(String)}.
* @param aevListener
* The listener that handles the implementation of the
* action.
* @return The action that was bound to the button.
*/
public Action addGlobalKeystroke(String eventName, String keystroke,
Consumer<ActionEvent> aevListener) {
Action act = new KeyedButtonAction(eventName, aevListener);
KeyStroke stroke = KeyStroke.getKeyStroke(keystroke);
this.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(stroke, eventName);
this.getActionMap().put(eventName, act);
this.setText(label);
return act;
}
}
|