1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package motej.demos.balanceboard;
17
18 import java.awt.Color;
19 import java.awt.FlowLayout;
20 import java.awt.Graphics2D;
21
22 import javax.swing.JLabel;
23 import javax.swing.JPanel;
24
25 import motejx.adapters.BalanceBoardDirectionAdapter;
26 import motejx.extensions.balanceboard.BalanceBoard;
27
28
29
30
31
32
33 public class BalanceBoardGraphicalPanel extends BalanceBoardDirectionAdapter {
34
35 private int x,y;
36
37 private JLabel xyLabel = new JLabel();
38
39 private JPanel panel = new JPanel() {
40 protected void paintComponent(java.awt.Graphics g) {
41 super.paintComponent(g);
42
43 if (x == 0 && y == 0) {
44 x = getWidth() / 2;
45 y = getHeight() / 2;
46 }
47
48 Graphics2D g2d = (Graphics2D) g;
49 Color bak = g2d.getColor();
50 g2d.setColor(Color.RED);
51 g2d.fillOval(x, y, 10, 10);
52 g2d.setColor(bak);
53 }
54 };
55
56 @Override
57 public void directionChanged(float x, float y) {
58 this.x += Math.round(x);
59 this.y -= Math.round(y);
60
61 if (this.x < 1)
62 this.x = 1;
63 if (this.x > panel.getWidth() - 1)
64 this.x = panel.getWidth() - 1;
65 if (this.y < 1)
66 this.y = 1;
67 if (this.y > panel.getHeight() - 1)
68 this.y = panel.getHeight() - 1;
69
70 xyLabel.setText("X: " + this.x + " - Y: " + this.y + " - x: " + Math.round(x) + " - y: " + Math.round(y));
71
72 panel.repaint();
73 }
74
75 public BalanceBoardGraphicalPanel(BalanceBoard board) {
76 board.addBalanceBoardListener(this);
77 panel.setLayout(new FlowLayout());
78 panel.add(xyLabel);
79 }
80
81 public JPanel getPanel() {
82 panel.setSize(400, 400);
83 return panel;
84 }
85 }