Commit | Line | Data |
---|---|---|
21c4e167 H |
1 | import java.awt.Container; |
2 | import java.awt.Graphics; | |
3 | import java.awt.Point; | |
4 | import java.awt.event.KeyEvent; | |
5 | import java.awt.event.KeyListener; | |
6 | import java.awt.event.WindowAdapter; | |
7 | import java.awt.event.WindowEvent; | |
8 | ||
9 | import javax.swing.JFrame; | |
10 | import javax.swing.JPanel; | |
11 | ||
12 | public class SketchPanel extends JPanel implements KeyListener { | |
13 | ||
14 | private Point startPoint = new Point(0, 0); | |
15 | ||
16 | private Point endPoint = new Point(0, 0); | |
17 | ||
18 | public SketchPanel() { | |
19 | addKeyListener(this); | |
20 | } | |
21 | ||
22 | public void keyPressed(KeyEvent evt) { | |
23 | int keyCode = evt.getKeyCode(); | |
24 | int d; | |
25 | if (evt.isShiftDown()) | |
26 | d = 5; | |
27 | else | |
28 | d = 1; | |
29 | if (keyCode == KeyEvent.VK_LEFT) | |
30 | add(-d, 0); | |
31 | else if (keyCode == KeyEvent.VK_RIGHT) | |
32 | add(d, 0); | |
33 | else if (keyCode == KeyEvent.VK_UP) | |
34 | add(0, -d); | |
35 | else if (keyCode == KeyEvent.VK_DOWN) | |
36 | add(0, d); | |
37 | } | |
38 | ||
39 | public void keyReleased(KeyEvent evt) { | |
40 | } | |
41 | ||
42 | public void keyTyped(KeyEvent evt) { | |
43 | } | |
44 | ||
45 | public boolean isFocusTraversable() { | |
46 | return true; | |
47 | } | |
48 | ||
49 | public void add(int dx, int dy) { | |
50 | endPoint.x += dx; | |
51 | endPoint.y += dy; | |
52 | Graphics g = getGraphics(); | |
53 | g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y); | |
54 | g.dispose(); | |
55 | startPoint.x = endPoint.x; | |
56 | startPoint.y = endPoint.y; | |
57 | } | |
58 | ||
59 | public static void main(String[] args) { | |
60 | JFrame frame = new JFrame(); | |
61 | frame.setTitle("Sketch"); | |
62 | frame.setSize(300, 200); | |
63 | frame.addWindowListener(new WindowAdapter() { | |
64 | public void windowClosing(WindowEvent e) { | |
65 | System.exit(0); | |
66 | } | |
67 | }); | |
68 | ||
69 | Container contentPane = frame.getContentPane(); | |
70 | contentPane.add(new SketchPanel()); | |
71 | ||
72 | frame.show(); | |
73 | } | |
74 | } | |
75 |