Java Reference
In-Depth Information
// Initialize the ball for the drop.
fDropPanel.reset ();
// Loop through animation frames
while (fThread!= null) {
// Sleep 25msecs between frames
try{Thread.sleep (25);
}
catch (InterruptedException e) {}
// Repaint drop panel for each new frame
fDropPanel.repaint ();
if (fDropPanel.isDone ()) fThread = null;
}
// Enable button for another drop
fDropButton.setEnabled (true);
} // actionPerformed
} // class DropApplet
The Drop2DPanel class is shown below. The panel calculates the position of
the ball for each increment of time between the frames and redraws the ball. It
reverses the ball when it hits the floor and also subtracts some speed to simulate
friction. Eventually, the ball comes to a rest and sets a flag that the drop simulation
is done.
import javax.swing.*;
import java.awt.*;
import java.text.*;
import java.util.*;
/** This JPanel subclass displays a falling ball. **/
public class Drop2DPanel extends JPanel
{
// Parameters for the drop
double fY = 0.0, fVy = 0.0;
// Conversion factor from cm to drawing units
double fYConvert = 0.0;
double fXPixel= 0.0, fYPixel = 0.0,
double fRadius = 0.0, fDiam = 0.0;
// starting point for ball in cm
double fY0 = 1000.0;
// Frame dimensions.
double fFrameHt, fFrameWd;
// Flag for drop status
boolean fDropDone = false;
Search WWH ::




Custom Search