1 import java.awt.event.MouseListener;
2 import java.awt.event.MouseEvent;
3 import javax.swing.JFrame;
4
5 import java.awt.event.KeyListener;
6 import java.awt.event.KeyEvent;
7 import javax.swing.KeyStroke;
8
9 /**
10 This frame contains a moving rectangle.
11 */
12 public class RectangleFrame3 extends JFrame
13 {
14 private static final int FRAME_WIDTH = 300;
15 private static final int FRAME_HEIGHT = 400;
16
17 private RectangleComponent3 scene;
18
19 class MousePressListener implements MouseListener
20 {
21 public void mousePressed(MouseEvent event)
22 {
23 int x = event.getX();
24 int y = event.getY();
25 scene.moveRectangleTo(x, y);
26 }
27
28 // Do-nothing methods
29 public void mouseReleased(MouseEvent event) {}
30 public void mouseClicked(MouseEvent event) {}
31 public void mouseEntered(MouseEvent event) {}
32 public void mouseExited(MouseEvent event) {}
33 }
34
35 class KeyStrokeListener implements KeyListener
36 {
37 public void keyPressed(KeyEvent event)
38 {
39 String key = KeyStroke.getKeyStrokeForEvent(event).toString().replace("pressed ", "");
40 if (key.equals("DOWN"))
41 {
42 scene.moveRectangleBy(0, 1);
43 }
44 else if (key.equals("UP"))
45 {
46 scene.moveRectangleBy(0, -1);
47 }
48 else if (key.equals("LEFT"))
49 {
50 scene.moveRectangleBy(-1, 0);
51 }
52 else if (key.equals("RIGHT"))
53 {
54 scene.moveRectangleBy(1, 0);
55 }
56 }
57 public void keyTyped(KeyEvent event) {}
58 public void keyReleased(KeyEvent event) {}
59 }
60
61 public RectangleFrame3()
62 {
63 scene = new RectangleComponent3();
64 add(scene);
65
66 MouseListener listener = new MousePressListener();
67 scene.addMouseListener(listener);
68
69 scene.addKeyListener(new KeyStrokeListener());
70 scene.setFocusable(true);
71
72 setSize(FRAME_WIDTH, FRAME_HEIGHT);
73 }
74 }