1   /*
2    * Copyright 2007-2008 Volker Fritzsch
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.nunchuk;
17  
18  import java.awt.Color;
19  import java.awt.Graphics2D;
20  import java.awt.Point;
21  import java.awt.geom.AffineTransform;
22  import java.awt.geom.Point2D;
23  
24  import javax.swing.JPanel;
25  
26  import motejx.extensions.nunchuk.NunchukCalibrationData;
27  
28  /**
29   * 
30   * <p>
31   * @author <a href="mailto:vfritzsch@users.sourceforge.net">Volker Fritzsch</a>
32   */
33  @SuppressWarnings("serial")
34  public class AnalogStickPanel extends JPanel {
35  	
36  	private NunchukCalibrationData nunchukCalibrationData;
37  	
38  	private AffineTransform trafo;
39  	
40  	private Point stickPoint;
41  	
42  	public NunchukCalibrationData getNunchukCalibrationData() {
43  		return nunchukCalibrationData;
44  	}
45  
46  	protected void paintComponent(java.awt.Graphics g) {
47  		super.paintComponent(g);
48  		
49  		int width = getWidth();
50  		int height = getHeight();
51  		
52  		Graphics2D g2 = (Graphics2D) g;
53  		Color fc = g2.getColor();
54  		
55  		g2.setColor(Color.BLACK);
56  		g2.drawOval((int) (width * 0.025), (int) (height * 0.025), (int) (width * 0.95), (int) (height * 0.95));
57  		
58  		if (trafo == null && nunchukCalibrationData != null) {
59  			Point min = nunchukCalibrationData.getMinimumAnalogPoint();
60  			Point max = nunchukCalibrationData.getMaximumAnalogPoint();
61  			
62  			double sx = width / (max.x - min.x);
63  			double sy = height / (max.y - min.y);
64  			trafo = AffineTransform.getScaleInstance(sx, sy);
65  		}
66  		
67  		if (trafo != null && stickPoint != null) {
68  			Point2D p = trafo.transform(stickPoint, null);
69  			g2.setColor(Color.BLUE);
70  			g2.fillOval((int) (p.getX() - width * 0.05), (int) (p.getY() - height * 0.05), (int) (width * 0.1), (int) (height * 0.1));
71  		}
72  		
73  		g2.setColor(fc);
74  		
75  	}
76  
77  	public void setNunchukCalibrationData(NunchukCalibrationData nunchukCalibrationData) {
78  		this.nunchukCalibrationData = nunchukCalibrationData;
79  	}
80  
81  	public void setStickPoint(Point stickPoint) {
82  		this.stickPoint = stickPoint;
83  	}
84  }