1   /*
2    * Copyright 2008 motej
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License. 
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   * <p>
31   * @author <a href="mailto:vfritzsch@users.sourceforge.net">Volker Fritzsch</a>
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  }