package org.opensourcephysics.sip.ch6; import java.awt.Color; import org.opensourcephysics.controls.*; import org.opensourcephysics.display.*; public class PendulumApp implements Animation { Control myControl; // contains the graph PlottingPanel plottingPanel = new PlottingPanel("Time", "Theta", "angle vs time"); DrawingFrame plottingFrame = new DrawingFrame(plottingPanel); // contains the animation DrawingPanel drawingPanel = new DrawingPanel(); DrawingFrame drawingFrame = new DrawingFrame(drawingPanel); Thread animationThread; DatasetCollection dataset; Pendulum pendulum; double dt; public PendulumApp() { pendulum = new Pendulum(); drawingPanel.setPreferredMinMax(-1.2, 1.2, -1.2, 1.2); drawingPanel.addDrawable(pendulum); dataset = new DatasetCollection(); dataset.setXYColumnNames(0, "time", "theta"); plottingPanel.addDrawable(dataset); } public void setControl(Control control) { myControl = control; resetAnimation(); } public void startAnimation() { animationThread = new Thread(this); animationThread.start(); // start the animation } public void initializeAnimation() { dt = myControl.getDouble("dt"); // time step double theta = myControl.getDouble("theta"); double omega = myControl.getDouble("omega"); double[] state = pendulum.getState(); pendulum.setState(theta, omega, state[2]); plottingPanel.repaint(); drawingPanel.repaint(); } public void stopAnimation() { Thread runningThread = animationThread; animationThread = null; // stop the animation try { // wait for the thread to die if (runningThread != null) { runningThread.join(); } } catch(InterruptedException e) {} updateControlValues(); } public void updateControlValues() { double[] state = pendulum.getState(); myControl.setValue("theta", state[0]); myControl.setValue("omega", state[1]); } public void stepAnimation() { stepPendulum(); plottingPanel.repaint(); drawingPanel.repaint(); updateControlValues(); } public void stepPendulum() { double[] state = pendulum.getState(); // get the state dataset.append(0, state[2], state[0]); // add data to the curve pendulum.step(dt); // advance the SHO state by dt } public void resetAnimation() { dataset.clear(); plottingPanel.repaint(); drawingPanel.repaint(); double[] state = pendulum.getState(); double theta = 1; double omega = 1; double t = 0; pendulum.setState(theta, omega, t); updateControlValues(); myControl.setValue("dt", 0.1); } public void run() { while(animationThread == Thread.currentThread()) { stepPendulum(); plottingPanel.render(); // paint the plot drawingPanel.render(); // paint the animation try { animationThread.sleep(100); } catch(InterruptedException ie) {} } } public static void main(String[] args) { Animation app = new PendulumApp(); AnimationControl control = new AnimationControl(app); app.setControl(control); } }