-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path71_KeyBindings
More file actions
89 lines (72 loc) · 2.6 KB
/
71_KeyBindings
File metadata and controls
89 lines (72 loc) · 2.6 KB
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
// Key Bindings = bind an Action to a KeyStroke
// don't require you to click a component to give it focus
// all Swing components use Key Bindings
// increased flexibility compared to KeyListeners
// can assign key strokes to individual Swing components
// more difficult to utilize and set up
<Main.java>
public class Main {
public static void main(String[] args){
Game game = new Game();
}
}
<Game.java>
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game {
JFrame frame;
JLabel label;
Action upAction;
Action downAction;
Action leftAction;
Action rightAction;
Game(){
frame = new JFrame("KeyBinding Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(420,420);
frame.setLayout(null);
label = new JLabel();
label.setBackground(Color.RED);
label.setBounds(100,100,100,100);
label.setOpaque(true);
upAction = new UpAction();
downAction = new DownAction();
leftAction = new LeftAction();
rightAction = new RightAction();
label.getInputMap().put(KeyStroke.getKeyStroke("UP"),"upAction");//keyStroke, actionMapKey
label.getActionMap().put("upAction",upAction);//key, action
label.getInputMap().put(KeyStroke.getKeyStroke("DOWN"),"downAction");
label.getActionMap().put("downAction",downAction);
label.getInputMap().put(KeyStroke.getKeyStroke("LEFT"),"leftAction");
label.getActionMap().put("leftAction",leftAction);
label.getInputMap().put(KeyStroke.getKeyStroke("RIGHT"),"rightAction");
label.getActionMap().put("rightAction",rightAction);
frame.add(label);
frame.setVisible(true);
}
public class UpAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
label.setLocation(label.getX(), label.getY()-10);
}
}
public class DownAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
label.setLocation(label.getX(), label.getY()+10);
}
}
public class LeftAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
label.setLocation(label.getX()-10, label.getY());
}
}
public class RightAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
label.setLocation(label.getX()+10, label.getY());
}
}
}