1 import javax.swing.JPanel;
2 import java.awt.Graphics;
3 import java.awt.*;
4
5 /*
6 * IPView.java
7 *
8 * Created on March 31, 2004, 5:57 PM
9 *
10 * Copyright 2004 Andrew Kaluzniacki
11 * All rights reserved.
12 * http://drewk.net
13 */
14
15 /**
16 * IPView provides a view of IPModel
17 * @author drew
18 */
19 public final class IPView extends JPanel {
20
21 private IPModel model;
22
23 /** Creates new form IPView */
24 public IPView() {
25 initComponents();
26 }
27
28 /** This method is called from within the constructor to
29 * initialize the form.
30 * WARNING: Do NOT modify this code. The content of this method is
31 * always regenerated by the Form Editor.
32 */
33 private void initComponents() {
34
35 setLayout(new java.awt.BorderLayout());
36
37 setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0)));
38 }
39
40
41 // Variables declaration - do not modify
42 // End of variables declaration
43
44 // http://java.sun.com/docs/books/tutorial/uiswing/14painting/practice.html
45
46 protected void paintComponent(Graphics g) {
47 super.paintComponent(g);
48 Graphics2D g2 = (Graphics2D)g; // in most cases (ours) this is a safe cast
49
50 // get the dimensions of the JPanel so that we can scale everything properly
51 Insets insets = getInsets();
52 int viewWidth = getWidth() - insets.left - insets.right;
53 int viewHeight = getHeight() - insets.top - insets.bottom;
54
55 // scale the size of the model to the size of the view.
56 // the constants are chosen for asthetics, but could be based on say
57 // the masses of the objects.
58 // Note that for the view to be physiclly correct, l and x must be
59 // correctly proportianal. ( FIXME - better explaination )
60
61 int blockWidth = viewWidth/10;
62 int blockHeight = viewHeight/10;
63 int penMassRadius = blockHeight/2;
64
65 double modelX = 0;
66 double modelPhi = 0;
67 int penLength = blockHeight * 3;
68
69 //
70 if (model != null) {
71 modelX = model.getX();
72 modelPhi = model.getPhi();
73 }
74
75
76 int blockX = (int)(modelX * penLength + viewWidth/2);
77 int blockY = viewHeight/2;
78 int penX = (int)(blockX + penLength * Math.sin(modelPhi));
79 int penY = (int)(blockY + penLength * Math.cos(modelPhi) - blockHeight);
80
81
82 // paint the block
83 g2.setColor(Color.blue);
84 g2.fill(new Rectangle(blockX - blockWidth/2, blockY - blockHeight ,blockWidth, blockHeight));
85
86
87 // paint the pendulum mass
88 g2.setColor(Color.green);
89 g2.fillOval(penX-penMassRadius, penY-penMassRadius, 2*penMassRadius, 2*penMassRadius);
90
91 // paint the rod
92 g2.drawLine(blockX,blockY -blockHeight , penX, penY);
93 }
94
95 /**
96 * associate a model with this view
97 */
98 public void setModel(IPModel aModel) {
99 model = aModel;
100 }
101
102 /**
103 * call when a state change in the model requires an update to the view
104 */
105 public void modelStateChanged() {
106 this.repaint();
107 }
108
109 }
110