Download Chapter 4: Detailed Design and Implementation

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Chapter 4: Detailed Design and Implementation
In designing this system, I have made reference to an existing physics simulation coding
retrieved from Physics Simulation and Java – Lecture 11B: A Simple Physics Simulation. [8]
The simulation proposed in this system was originally an Applet. I have adopted the method
which this existing system used to make simulation. However, I have also made some
changes to the coding in terms of:

Changing it from using AWT graphics into SWING graphics.

Create a more user friendly and controllable user interface.

Enlarge the display panel so that user can have a better view of the simulation.

Alter the coding so that it will accept parameters from users.

Set the value of weight as a default value (because its influence on an object is
negligible)

Making it into a simulation which will generate object in real-time (previously it is
just an animation looping whenever the “Drop” button is being pressed.

Added features such as the influences of ball type and gravitational acceleration on
the bouncing of a ball.

While watching the simulation, users are able to freeze the simulation in order to
study the time, velocity and the position of the ball.

A mini scale has been included at the side of the screen to allow users to make
comparison.

In order to promote the sense of realism, the ball will be smaller when it is at a
higher location and different type of ball will yield different kind of colour.

Users can save the input parameters.

Users can also retrieve the saved information in an archive folder.

Provide tutorial and help function to promote users’ understanding in this topic.
56
In terms of system design, a few key design decisions were made:

The class interface will serve as the main file. It has also been made into a static file
in order to allow the passing of variable and threads.

The initial velocity of the ball in x-direction has been defined by using the random
function. In real life situation, the initial push or thrust will vary depending on the
thrower, therefore resulting in larger curve.

The display value for the changing variable is calculated simultaneously with the
drawing, using the same input information. The calculation is based on the actual
values of the input, which unlike the calculation in drawing, the calculation has been
scaled to fit into the drawing canvas.

The class ObjectToDraw is an abstract class. It can be overridden by its subclass,
which is class Circle.
4.1 Detailed Design
In the design below, each class is developed in isolation. However, the classes can be linked
together due to the value passing and the inheritance relationship among some classes.
Interface
- g: Graphics
- ja: FallingObject
- In: Interface
- tut: tutorial
- fc: JFileChooser
- jButtonHelp: JButton
- jButtonPause: JButton
- jButtonReset: JButton
- jButtonRetrieve: JButton
- jButtonSave: JButton
- jButtonStart: JButton
- jButtonTutorial: JButton
- jComboBoxGField: JComboBox
- jComboBoxHeight: JComboBox
- jComboBoxType: JComboBox
- jLabelGField: JLabel
- jLabelHeight: JLabel
- jLabelTime: JLabel
- jLabelType: JLabel
- jLabelVelocity: JLabel
57
- jLabelWeight: JLabel
- jOptionPaneStartUp: JOptionPane
- jPanelCVariable: JPanel
- jPanelDraw: JPanel
- jPanelMVariable: JPanel
- jTextFieldTime: JTextField
- jTextFieldvelocity: JTextField
- jTextFieldWeight: JTextField
- test: JComboBox
- tut: tutorial
+ main (String args[])
+ Interface()
+ initComponents()
+ jButtonHelpactionPerformed(java.awt.event.ActionEvent evt)
+ jButtonPauseactionPerformed(java.awt.event.ActionEvent evt)
+ jButtonResetActionPerformed(java.awt.event.ActionEvent evt)
+ jButtonSaveactionPerformed(java.awt.event.ActionEvent evt)
+ jButtonStartactionPerformed(java.awt.event.ActionEvent evt)
+ jButtonTutorialactionPerformed(java.awt.event.ActionEvent evt)
+ set_jTextFieldTime(double Time)
+ set_jTextFieldVelocity(double Velocity)
Table 26: Detailed design of Class Interface
FallingObject
- i_Interface: Interface
- shoot: BoxShoot
+ init(Interface i_Interface)
+ actionPerformed(ActionEvent e)
+ Insets getInsets()
+ reset()
+ resume()
+ sleep()
+ stop()
Table 27: Detailed design of class FallingObject
BoxShoot
- ball: Circle
- controlCal: int
58
- dX: int
- dY: int
- deltaT: double
- drawThread: Thread
- frameRate: int
- gPhysical: double
- i_Interface: Interface
- initCanvas: Boolean
- offScrImg: Image
- physicalHeight: double
- r: int
- speedUp: double
- stopRepaint: boolean
+ BoxShoot :: Canvas : Runnable
+ getCal(int value)
+ getGField(double value)
+ getHeight(double value)
+ getRadius(int value)
+ init()
+ paint(Graphics g)
+ reset()
+ resume()
+ run()
+ setDrawing()
+ sleep()
+ start()
+ stop()
+ update(Graphics g)
Table 28: Detailed design of class BoxShoot
Circle
- FrictionLoss: double
- VxInit: double
- VxStop: double
- VyCalInit: double
- VyCalStop: double
- VyInit: double
- Vystop: double
- c: Color
- currentX: int
- currentY: int
- drawXInit: int
- drawYInit: int
59
- g: double
- gCal: double
- lastX: int
- lastY: int
- onFloor: Boolean
- radius: int
- time: double
- x: double
- xRightBound: double
- xStop: Boolean
- y: double
- yBottomBound: double
- yStop: boolean
+ Circle(int centerX, int centerY, int radius, int dX, int dY, double grav)
+ clipToAffectedArea(Graphics g, int oldx, int oldy, int newx, int newy, int width, int height)
+ draw(Graphics g)
+ drawline(Graphics g)
+ getFrictionLoss(double value)
+ getGField(double value)
+ label2(Graphics g)
+ label4(Graphics g)
+ label6(Graphics g)
+ label8(Graphics g)
+ label10(Graphics g)
+ move(double deltaT)
+ reset()
Table 29: Detailed design of class Circle
ObjectToDraw
- Vtot: double
- Vx: double
- Vy: double
- VyCal: double
- areaX: int
- areaY: int
- centerX: int
- centerY: int
- color: Color
- drawX: int
-drawY: int
- dx: int
- dyLint
- dyCal: int
60
- toggleSign: double
+ ObjectToDraw(int centerX, int centerY, int dx, int dy, int dX, int dY)
+ draw(Graphics g)
+ getColor(Color c)
+ move(double deltaT)
Table 30: Detailed design of class ObjectToDraw
tutorial
- jButton1: JButton
- jlable1: JLabel
- jPanel1: JPanel
- jScrollPane1: JScrollPane
- jTextPane1: JTextPane
- tut: tutorial
+ tutorial()
+ initComponents()
Table 31: Detailed design of class tutorial
61
4.2 Package Diagram
Bouncing ball simulation
Interface
Interface
BoxShoot
FallingObject
Circle
ObjectToDraw
Figure 17: The package diagram for Bouncing Ball Simulation.
62
4.3 Source Code
Interface.java
package GravitySimulation;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.filechooser.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
/**
*
* @author Ng Bai Hui
*/
public class Interface extends javax.swing.JFrame {
Graphics g;
FallingObject ja;
// BoxShoot bs;
static Interface In;
static tutorial tut;
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
In = new Interface();
In.setVisible(true);
//new Interface().setVisible(true);
}
});
}
/** Creates new form Design */
public Interface() {
initComponents();
}
63
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
public void initComponents() {
jPanelDraw = new javax.swing.JPanel();
jPanelMVariable = new javax.swing.JPanel();
jLabelHeight = new javax.swing.JLabel();
jComboBoxHeight = new javax.swing.JComboBox();
jLabelWeight = new javax.swing.JLabel();
jTextFieldWeight = new javax.swing.JTextField();
jLabelType = new javax.swing.JLabel();
jComboBoxType = new javax.swing.JComboBox();
jLabelGField = new javax.swing.JLabel();
jComboBoxGField = new javax.swing.JComboBox();
jButtonStart = new javax.swing.JButton();
jButtonPause = new javax.swing.JButton();
jButtonPause.setEnabled(false);
jButtonReset = new javax.swing.JButton();
jPanelCVariable = new javax.swing.JPanel();
jLabelTime = new javax.swing.JLabel();
jTextFieldTime = new javax.swing.JTextField();
jLabelVelocity = new javax.swing.JLabel();
jTextFieldVelocity = new javax.swing.JTextField();
jButtonSave = new javax.swing.JButton();
jButtonRetrieve = new javax.swing.JButton();
jButtonTutorial = new javax.swing.JButton();
jButtonHelp = new javax.swing.JButton();
//
//
jLabelDistance = new javax.swing.JLabel();
jTextFieldDistance = new javax.swing.JTextField();
//
final JFileChooser fc = new JFileChooser("C:\\Users\\ChuEn\\Desktop\\Bouncing Ball
Simulation\\archives");
final JFileChooser fc = new JFileChooser();
jOptionPaneStartUp = new javax.swing.JOptionPane();
String d = "This is a physics simulator on Gravity\n\n" +
"Steps:\n" +
"1. Select a value for height.\n" +
"2. Select the type of ball and gravity field\n" +
"3. Click on the Start button to initiate the simulation\n" +
"4. Click on the Reset button to start another new simulation\n" +
"5. Click on the Save Data button to store the generated values\n\n" +
64
"Additional tutorial and help can be found in the system.";
jOptionPaneStartUp.showMessageDialog(null,
d,
JOptionPane.INFORMATION_MESSAGE);
"User
Guide",
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Law of Physics Simulation: Gravity");
setBackground(new java.awt.Color(255, 255, 255));
setBounds(new java.awt.Rectangle(0, 0, 0, 0));
setResizable(false);
jPanelDraw.setBackground(new java.awt.Color(255, 255, 255));
jPanelDraw.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanelDraw.setPreferredSize(new java.awt.Dimension(296, 340));
javax.swing.GroupLayout jPanelDrawLayout = new javax.swing.GroupLayout(jPanelDraw);
jPanelDraw.setLayout(jPanelDrawLayout);
jPanelDrawLayout.setHorizontalGroup(
jPanelDrawLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 294, Short.MAX_VALUE));
jPanelDrawLayout.setVerticalGroup(
jPanelDrawLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 338, Short.MAX_VALUE));
jPanelMVariable.setBorder(javax.swing.BorderFactory.createTitledBorder("Manipulated Variable"));
jLabelHeight.setText("Height (m)");
jComboBoxHeight.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"2", "4", "6", "8",
"10"}));
jLabelWeight.setText("Weight (kg)");
jTextFieldWeight.setEditable(false);
jTextFieldWeight.setText("1.0");
jLabelType.setText("Types of Ball");
jComboBoxType.setModel(new
javax.swing.DefaultComboBoxModel(new
String[]{"Baseball",
"Basketball", "Football", "Golf Ball", "Metal Ball", "Ping Pong", "Superball", "Tennis Ball"}));
jLabelGField.setText("Gravity Field");
jComboBoxGField.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Earth", "Jupiter",
"Mars", "Mercury", "Moon", "Sun", "Venus"}));
jButtonStart.setText("Start");
jButtonStart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonStartactionPerformed(evt);
65
}
});
jButtonPause.setText("Pause");
jButtonPause.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonPauseactionPerformed(evt);
}
});
jButtonReset.setText("Reset");
jButtonReset.setEnabled(false);
jButtonReset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonResetActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelMVariableLayout = new javax.swing.GroupLayout(jPanelMVariable);
jPanelMVariable.setLayout(jPanelMVariableLayout);
jPanelMVariableLayout.setHorizontalGroup(
jPanelMVariableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMVariableLayout.createSequentialGroup()
.addContainerGap().addGroup(jPanelMVariableLayout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMVariableLayout.createSequentialGroup()
.addGroup(jPanelMVariableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEA
DING)
.addComponent(jLabelHeight).addComponent(jLabelWeight)).addGap(35, 35, 35)
.addGroup(jPanelMVariableLayout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextFieldWeight)
.addComponent(jComboBoxHeight, 0, 68, Short.MAX_VALUE)))
.addGroup(jPanelMVariableLayout.createSequentialGroup()
.addGroup(jPanelMVariableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEA
DING)
.addComponent(jComboBoxType,
javax.swing.GroupLayout.PREFERRED_SIZE,
87,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelType)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.R
ELATED)
.addGroup(jPanelMVariableLayout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelGField)
.addComponent(jComboBoxGField,
javax.swing.GroupLayout.PREFERRED_SIZE,
82,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanelMVariableLayout.createSequentialGroup()
.addComponent(jButtonStart)
66
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonPause)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonReset)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
jPanelMVariableLayout.setVerticalGroup(
jPanelMVariableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMVariableLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelMVariableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BAS
ELINE)
.addComponent(jLabelHeight)
.addComponent(jComboBoxHeight, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18).addGroup(jPanelMVariableLayout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelWeight)
.addComponent(jTextFieldWeight, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18).addGroup(jPanelMVariableLayout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelType).addComponent(jLabelGField))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanelMVariableLayout.createParallelGroup(javax.swing.GroupLayout
.Alignment.BASELINE)
.addComponent(jComboBoxType, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBoxGField,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18).addGroup(jPanelMVariableLayout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonStart).addComponent(jButtonPause)
.addComponent(jButtonReset)).addContainerGap(32, Short.MAX_VALUE)));
jPanelCVariable.setBorder(javax.swing.BorderFactory.createTitledBorder("Changing Variable"));
jLabelTime.setText("Time (s)");
jTextFieldTime.setEditable(false);
jLabelVelocity.setText("Velocity (m/s)");
jTextFieldVelocity.setEditable(false);
//
//
jLabelDistance.setText("Distance (m)");
jTextFieldDistance.setEditable(false);
javax.swing.GroupLayout jPanelCVariableLayout = new javax.swing.GroupLayout(jPanelCVariable);
jPanelCVariable.setLayout(jPanelCVariableLayout);
jPanelCVariableLayout.setHorizontalGroup(
67
jPanelCVariableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelCVariableLayout.createSequentialGroup().addContainerGap()
.addGroup(jPanelCVariableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEA
DING)
.addComponent(jLabelVelocity).addComponent(jLabelTime))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelCVariableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEA
DING)
.addComponent(jTextFieldTime,
javax.swing.GroupLayout.DEFAULT_SIZE,
138,
Short.MAX_VALUE)
.addComponent(jTextFieldVelocity,
javax.swing.GroupLayout.DEFAULT_SIZE,
138,
Short.MAX_VALUE))
.addContainerGap()));
jPanelCVariableLayout.setVerticalGroup(
jPanelCVariableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelCVariableLayout.createSequentialGroup()
.addContainerGap().addGroup(jPanelCVariableLayout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelTime).addComponent(jTextFieldTime,
javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)).addGap(18, 18, 18)
.addGroup(jPanelCVariableLayout.createParallelGroup(javax.swing.GroupLayout
.Alignment.BASELINE).addComponent(jLabelVelocity).addComponent(jTextFieldVelocity,
javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)).addContainerGap(19, Short.MAX_VALUE)));
jButtonSave.setText("Save Data");
jButtonSave.setEnabled(false);
jButtonSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonSaveactionPerformed(evt);
}
});
jButtonTutorial.setText("Tutorial");
jButtonTutorial.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonTutorialactionPerformed(evt);
}
});
jButtonRetrieve.setText("Retrieve Data");
jButtonRetrieve.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == jButtonRetrieve) {
68
int i = fc.showOpenDialog(Interface.this);
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (i == JFileChooser.APPROVE_OPTION) {
File fileToOpen = fc.getSelectedFile();
try {
Desktop.getDesktop().open(fileToOpen);
} catch (Exception exception) {
System.out.println("Problem occour when to open the file");
}
}
//
}
// jButtonRetrieveActionPerformed(evt);
}
});
jButtonHelp.setText("Help");
jButtonHelp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonHelpactionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup().addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelDraw, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup().addComponent(jButtonTutorial)
.addGap(18, 18, 18).addComponent(jButtonHelp,
javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanelCVariable, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(jPanelMVariable,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jButtonSave, javax.swing.GroupLayout.PREFERRED_SIZE,
95, javax.swing.GroupLayout.PREFERRED_SIZE).addGap(18, 18, 18)
.addComponent(jButtonRetrieve))).addContainerGap(22, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup().addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
69
.addGroup(layout.createSequentialGroup()
.addComponent(jPanelDraw, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(9, 9, 9)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonTutorial)
.addComponent(jButtonHelp)))
.addGroup(layout.createSequentialGroup()
.addComponent(jPanelMVariable, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelCVariable, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonSave).addComponent(jButtonRetrieve))))
.addContainerGap(26, Short.MAX_VALUE)));
pack();
}// </editor-fold>
public void jButtonStartactionPerformed(java.awt.event.ActionEvent evt) {
// double height = Double.parseDouble(jTextField1.getText());
// InputData.setHeight(height);
jButtonSave.setEnabled(true);
jButtonReset.setEnabled(true);
boolean b_checkNoError = false;
double weight = 0;
double height = 0;
double friction = 0;
double gravity = 0;
String type = "";
double distance = 0.0;
//try to parse Height
try {
//
height = Double.parseDouble(jTextFieldHeight.getText());
String getHeight = (String) jComboBoxHeight.getSelectedItem();
double h = Double.parseDouble(getHeight);
BoxShoot.getHeight(h);
if (h == 2) {
BoxShoot.getRadius(30);
BoxShoot.getCal(314);
} else if (h == 4) {
BoxShoot.getRadius(40);
BoxShoot.getCal(317);
} else if (h == 6) {
BoxShoot.getRadius(50);
BoxShoot.getCal(324);
} else if (h == 8) {
BoxShoot.getRadius(60);
70
BoxShoot.getCal(327);
} else { // h = 10
BoxShoot.getRadius(70);
BoxShoot.getCal(330);
}
} catch (Exception e) {
}
//try parse Weight
//
try {
//
weight = Double.parseDouble(jTextFieldWeight.getText());
//
//
} catch (Exception e) {
//
JOptionPane.showMessageDialog(null, "Weight must to be a double value.", "Input error",
JOptionPane.ERROR_MESSAGE);
//
return;
//
}
try {
String getType = (String) jComboBoxType.getSelectedItem();
System.out.println(getType);
if (getType.equalsIgnoreCase("baseball")) {
friction = 0.34; //0.68
Circle.getFrictionLoss(friction);
ObjectToDraw.getColor(Color.LIGHT_GRAY);
} else if (getType.equalsIgnoreCase("basketball")) {
friction = 0.22; //0.44
Circle.getFrictionLoss(friction);
ObjectToDraw.getColor(Color.red);
} else if (getType.equalsIgnoreCase("football")) {
friction = 0.30; //0.60
Circle.getFrictionLoss(friction);
ObjectToDraw.getColor(Color.blue);
} else if (getType.equalsIgnoreCase("golf ball")) {
friction = 0.32; //0.64
Circle.getFrictionLoss(friction);
ObjectToDraw.getColor(Color.gray);
} else if (getType.equalsIgnoreCase("metal ball")) {
friction = 0.01; //0.02
Circle.getFrictionLoss(friction);
ObjectToDraw.getColor(Color.black);
} else if (getType.equalsIgnoreCase("ping pong")) {
friction = 0.44; //0.85
Circle.getFrictionLoss(friction);
ObjectToDraw.getColor(Color.yellow);
} else if (getType.equalsIgnoreCase("tennis ball")) {
friction = 0.25; // 0.51
Circle.getFrictionLoss(friction);
ObjectToDraw.getColor(Color.green);
} else { //Superball
71
friction = 0.10; //0.19
Circle.getFrictionLoss(friction);
ObjectToDraw.getColor(Color.pink);
}
} catch (Exception e) {
}
try {
String getGField = (String) jComboBoxGField.getSelectedItem();
//
System.out.println(getGField);
//Earth", "Jupiter", "Mars", "Mercury", "Moon"}));
if (getGField.equalsIgnoreCase("earth")) {
gravity = 981.;
BoxShoot.getGField(gravity);
Circle.getGField(gravity);
} else if (getGField.equalsIgnoreCase("jupiter")) {
gravity = 2593.;
BoxShoot.getGField(gravity);
Circle.getGField(gravity);
} else if (getGField.equalsIgnoreCase("mars")) {
gravity = 372.;
BoxShoot.getGField(gravity);
Circle.getGField(gravity);
} else if (getGField.equalsIgnoreCase("mercury")) {
gravity = 370.;
BoxShoot.getGField(gravity);
Circle.getGField(gravity);
} else if (getGField.equalsIgnoreCase("sun")) {
gravity = 27410.;
BoxShoot.getGField(gravity);
Circle.getGField(gravity);
} else if (getGField.equalsIgnoreCase("venus")) {
gravity = 887.;
BoxShoot.getGField(gravity);
Circle.getGField(gravity);
} else { //getGField == "Moon"
gravity = 163.;
BoxShoot.getGField(gravity);
Circle.getGField(gravity);
}
} catch (Exception e) {
}
if (ja == null) {
ja = new FallingObject();
ja.init(In);
}
ja.actionPerformed(evt);
jButtonPause.setEnabled(true);
72
jButtonStart.setEnabled(false);
jPanelDraw.setSize(296, 340);
jPanelDraw.add(ja);
jPanelDraw.show();
//
jButtonStart.addActionListener(this);
}
public void jButtonPauseactionPerformed(java.awt.event.ActionEvent evt) {
try {
if (jButtonPause.getText().equals("Pause")) {
jButtonPause.setText("Resume");
ja.sleep();
} else {
jButtonPause.setText("Pause");
ja.resume();
}
} catch (Exception e) {
}
}
public void jButtonTutorialactionPerformed(java.awt.event.ActionEvent evt) {
try {
tut = new tutorial();
tut.setVisible(true);
} catch (Exception e) {
System.out.println("Cannot open tutorial");
}
}
public void jButtonSaveactionPerformed(java.awt.event.ActionEvent evt) {
//
jButton4ActionPerformed(evt);
double weight;
jButtonSave.setEnabled(false);
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
DateFormat dateFormatFile = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
try {
String getHeight = (String) jComboBoxHeight.getSelectedItem();
double h = Double.parseDouble(getHeight);
weight = Double.parseDouble(jTextFieldWeight.getText());
String getType = (String) jComboBoxType.getSelectedItem();
String getGField = (String) jComboBoxGField.getSelectedItem();
73
double g = 0.0;
if (getGField.equalsIgnoreCase("earth")) {
g = 9.81;
} else if (getGField.equalsIgnoreCase("jupiter")) {
g = 25.93;
} else if (getGField.equalsIgnoreCase("mars")) {
g = 3.72;
} else if (getGField.equalsIgnoreCase("mercury")) {
g = 3.70;
} else { //getGField == "Moon"
g = 1.63;
}
String filename = (String) dateFormatFile.format(date);
double time = Double.parseDouble(jTextFieldTime.getText());
double velocity = Double.parseDouble(jTextFieldVelocity.getText());
// Create a new file output stream
// connected to "myfile.txt"
out = new FileOutputStream("archives//" + filename + ".txt");
// Connect print stream to the output stream
p = new PrintStream(out);
p.println("-----------------------------");
p.println(dateFormat.format(date));
p.println("-----------------------------");
p.println("Height\t\t\t: " + h + " m");
p.println("Weight, by default\t\t: " + weight + " kg");
p.println("Type of ball\t\t: " + getType);
p.println("Gravity field\t\t: " + getGField);
p.println("Gravitational acceleration\t: " + g + " ms^-2");
p.println("Time taken\t\t: " + time + " s");
//
p.println("Total distance travelled\t: " + distance + "m");
//
p.println("Velocity\t\t\t: " + velocity + " ms^-2");
p.println("--------------------------------------------------------");
p.close();
//CopyFile.copyfile("temp.txt", "archives//" + filename + ".txt");
System.out.println("Save Successful");
JOptionPane.showMessageDialog(null,
"Data
Saved!",
JOptionPane.INFORMATION_MESSAGE);
"Save
Info",
} catch (Exception e) {
System.err.println("Error writing to file");
JOptionPane.showMessageDialog(null, "Error!", "Save Info", JOptionPane.ERROR_MESSAGE);
}
}
private void jButtonResetActionPerformed(java.awt.event.ActionEvent evt) {
ja.reset();
jButtonPause.setEnabled(false);
74
jButtonStart.setEnabled(true);
jButtonSave.setEnabled(false);
jButtonReset.setEnabled(false);
jTextFieldWeight.setText("1.0");
jTextFieldTime.setText("");
jTextFieldVelocity.setText("");
//
jTextFieldDistance.setText("");
jButtonPause.setText("Pause");
}
public void jButtonHelpactionPerformed(java.awt.event.ActionEvent evt) {
try {
System.out.println("Successfully open help");
String a = "1. Select a height value.\n" +
"2. By default, the weight is set to 1.0kg.\n" +
"3. Select the types of ball.\n" +
"4. Select the gravity field.\n" +
"5. Click on the Start button to initiate the simulation.\n" +
"6. Click on the Pause button to freeze the simulation.\n" +
"7. Click on the Reset button to restart another simulation.\n" +
"8. Create a folder named 'archives' in the location of jar file.\n" +
"9. Click on the Save Data button to store the generated values.\n" +
"10. Click on the Retrieve Data button to open the archives.";
JOptionPane.showMessageDialog(null, a, "Help", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
System.out.println("Error in help...");
}
}
public void set_jTextFieldVelocity(double Velocity) {
try {
jTextFieldVelocity.setText(Double.toString(Velocity));
} catch (Exception e) {
}
}
public void set_jTextFieldTime(double Time) {
try {
jTextFieldTime.setText(Double.toString(Time));
} catch (Exception e) {
}
}
private javax.swing.JButton jButtonHelp;
private javax.swing.JButton jButtonPause;
private javax.swing.JButton jButtonReset;
private javax.swing.JButton jButtonRetrieve;
private javax.swing.JButton jButtonSave;
private javax.swing.JButton jButtonStart;
private javax.swing.JButton jButtonTutorial;
75
private javax.swing.JComboBox jComboBoxGField;
private javax.swing.JComboBox jComboBoxHeight;
private javax.swing.JComboBox jComboBoxType;
private javax.swing.JComboBox test;
private javax.swing.JLabel jLabelGField;
private javax.swing.JLabel jLabelHeight;
private javax.swing.JLabel jLabelTime;
private javax.swing.JLabel jLabelType;
private javax.swing.JLabel jLabelVelocity;
private javax.swing.JLabel jLabelWeight;
private javax.swing.JPanel jPanelCVariable;
private javax.swing.JPanel jPanelDraw;
private javax.swing.JPanel jPanelMVariable;
private javax.swing.JTextField jTextFieldTime;
private javax.swing.JTextField jTextFieldVelocity;
private javax.swing.JTextField jTextFieldWeight;
private javax.swing.JOptionPane jOptionPaneStartUp;
private javax.swing.JFileChooser fc;
// End of variables declaration
}
FallingObject.java
package GravitySimulation;
/*
This applet simulates an object falling with
a constant gravitational acceleration.
*/
/*
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import GravitySimulation.Interface.*;
public class FallingObject extends JApplet implements ActionListener {
GravitySimulation.BoxShoot shoot;
Interface i_Interface;
/*--------------------------------------------------*/
//
public void init(Interface i_Interface) {
this.i_Interface = i_Interface;
setSize(296, 340);
shoot = new GravitySimulation.BoxShoot(this.i_Interface);
add(shoot);
76
}
public void actionPerformed(ActionEvent e) {
shoot.start();
}
public void stop()
{
shoot.stop();
}
public void sleep()
{
shoot.sleep();
}
public void resume()
{
shoot.resume();
}
public void reset()
{
shoot.reset();
}
/*--------------------------------------------------*/
public Insets getInsets() {
return new Insets(2, 2, 2, 2);
}
}
BoxShoot.java
package GravitySimulation;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.applet.*;
import GravitySimulation.*;
/*###################################################*/
public class BoxShoot extends Canvas implements Runnable {
int dY, dX;
static int r;
Image offScrImg;
Circle ball;
boolean initCanvas = true;
Thread drawThread;
77
int frameRate;
double deltaT;
double speedUp;
static double gPhysical;
static double physicalHeight;
boolean stopRepaint = false;
Interface i_Interface;
static int controlCal;
/*- -------------------------------------------------*/
//
public BoxShoot(Interface i_Interface) {
this.i_Interface = i_Interface;
setBackground(Color.white);
dY = 340;
dX = 296;
setSize(dX, dY);
init();
}
/*--------------------------------------------------*/
//
public static void getHeight(double value) {
physicalHeight = value * 100;
System.out.println("Height: " + physicalHeight + "cm");
}
public static void getGField(double value) {
gPhysical = value;
System.out.println("Gravity: " + gPhysical + "cms^-2");
}
public static void getRadius(int value) {
r = value;
//System.out.println("Radius = " + dY/r);
}
public static void getCal(int value) {
controlCal = value;
}
/*--------------------------------------------------*/
public void init() {
// Get the drawing area of the applet
// Choose some parameter for the object to drop
int radius = dY / r;
//
System.out.println("Radius = " + radius);
//int radius = dY / 30;
int x0 = 2 * radius;
int y0 = 2 * radius;
// These parameters separate thread animation
78
// frame rates from the physical time of the
// falling object.
frameRate = 10;
speedUp = 1.0;
deltaT = frameRate / 1000.0;
deltaT *= speedUp;
//gPhysical = 980.;// = 9.8cm/s**2 // also subjected to modify
//physicalHeight = 200.0; // subjected to modify
// Scale physical g units to the graphical pixel units
// Let the frame represent a 200cm in height.
double g = gPhysical * (controlCal / physicalHeight);
//double g = gPhysical * (dY / physicalHeight);
// Create the object to drop
ball = new Circle(x0, y0, radius, dX, dY, g);
// set it's initial velocity
ball.VxInit = 20.0;
ball.VyInit = 0.0;
// Lowest velocity before declaring stopped
ball.Vxstop = 1.00;
ball.Vystop = 1.00;
//
}
/*--------------------------------------------------*/
public void reset() {
initCanvas = true;
this.stop();
stopRepaint = true;
repaint();
ball.time = 0.0;
//
ball.FrictionLoss=0.0;
//
ball.radius=340/30;
}
public void resume() {
stopRepaint = false;
}
public void setDrawing() {
init();
}
79
public void start() {
stopRepaint = false;
if (drawThread != null) {
stop();
}
setDrawing();
ball.reset();
initCanvas = true;
drawThread = new Thread(this);
drawThread.start();
}
/*--------------------------------------------------*/
public void stop() {
drawThread = null;
// Give this thread time to jump out of its loop in run()
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
}
/*--------------------------------------------------*/
public void run() {
repaint();
while (drawThread != null) {
// Use sleep to pause between movements
try {
Thread.sleep(frameRate);
} catch (InterruptedException e) {
}
if (ball.xStop && ball.yStop) {
stop();
break;
}
if (!stopRepaint) {
ball.move(deltaT);
//
//
//
//
//
//
//
this.i_Interface.set_jTextFieldVelocity(ball.VyCal);
//dyCal = deltaT * VyCal + 0.5 * gCal * deltaT * deltaT;
this.i_Interface.set_jTextFieldDistance(ball.dyCal);
this.i_Interface.set_jTextFieldTime(ball.time += 0.01);
try {
String filename = "temp.txt";
boolean append = true;
FileWriter file = new FileWriter(filename, append);
int j = 0;
for (int i = 0; i < 10; i++) {
80
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
j++;
if (j == 50) {
// file.write("\r\n");
String t = "Time: " + (ball.time += 0.01);
String v = "Velocity: " + ball.VyCal;
file.write("\t"+t+"\n");//appends the string to the file
file.write("\t"+v+"\n");//appends the string to the file
j = 0;
}
file.close();
}
//System.out.println("Save Successful");
} catch (IOException ioe) {
System.err.println("IOException: " + ioe.getMessage());
}
repaint();
}
}
System.out.println("Drop finished");
}
/*--------------------------------------------------*/
public synchronized void update(Graphics g) {
// Create an offscreen image and then get its graphics context
if (offScrImg == null) {
offScrImg = createImage(dX, dY);
}
Graphics og = offScrImg.getGraphics();
// Now draw on the offscreen image.
paint(og);
// Don't bother to call paint, just draw the offscreen image
// to the screen.
g.drawImage(offScrImg, 0, 0, this);
// Get rid of the offscreen graphics context. Can't unclip a graphics
// context so have to get a new one next time around.
og.dispose();
}
/*--------------------------------------------------*/
public synchronized void sleep() {
stopRepaint = true;
}
public synchronized void paint(Graphics g) {
81
if (initCanvas) {
g.setColor(Color.white);
g.fillRect(0, 0, dX, dY);
initCanvas = false;
}
if (!stopRepaint) {
if (physicalHeight == 200) {
ball.label2(g);
} else if (physicalHeight == 400) {
ball.label4(g);
} else if (physicalHeight == 600) {
ball.label6(g);
} else if (physicalHeight == 800) {
ball.label8(g);
} else if (physicalHeight == 1000) {
ball.label10(g);
}
ball.drawline(g);
ball.draw(g);
}
}
}
Circle.java
package GravitySimulation;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import GravitySimulation.*;
// Create a circle class that extends the base
// drawing class
public class Circle extends ObjectToDraw {
int lastX, lastY, currentX, currentY;
int drawXInit, drawYInit;
int radius;
double g;
//gravity constant - defined in BoxShoot.java - default:9.8
static double FrictionLoss;
//also energy lost - default 0.05
double time = 0.0;
//time for simulation
double Vxstop, Vystop;
//stop velocity for ball
double x, y;
//coordinate for plotting
double xRightBound, yBottomBound; //position of ball on ground
double VxInit, VyInit;
//to initiate the velocity of the ball
double VyCalInit, VyCalstop;
Color c;
82
boolean xStop, yStop, onFloor;
static double gCal;
/*---------------------------------------------------*/
public static void getFrictionLoss(double value) {
FrictionLoss = value;
System.out.println("Friction Loss: " + FrictionLoss);
}
/*---------------------------------------------------*/
public static void getGField(double value) {
gCal = value / 100;
}
/*---------------------------------------------------*/
Circle(int centerX, int centerY, int radius,
int dX, int dY, double grav) {
// super constructor must be called in first line.
super(centerX, centerY, 2 * radius, 2 * radius, dX, dY);
this.radius = radius;
drawXInit = drawX;
drawYInit = drawY;
// FrictionLoss = 0.05;
time = 0.0;
System.out.println(grav);
g = grav;
// In pixels per sec**2
// the gravity has ady been scaled in BoxShoot.java
// Scale physical g units to the graphical pixel units
// Let the frame represent a 200cm in height.
VxInit = Vx;
VyInit = Vy;
VyCalInit = VyCal;
Vxstop = Vx * 0.02;
Vystop = Vy * 0.02;
VyCalstop = Vy * 0.02;
// speed chose to stop the ball (small enough to deceive the eyes)
xRightBound = areaX - 2 * radius; // right side frame - wall
yBottomBound = areaY - 2 * radius - 1;
}
/*---------------------------------------------------*/
public void reset() {
drawX = drawXInit;
drawY = drawYInit;
lastX = drawX;
lastY = drawY;
currentX = drawX;
83
currentY = drawY;
// Use double value for physical position.
x = drawX;
y = drawY;
Vx = VxInit * (0.50 + 1.50 * Math.random());
Vy = VyInit;
VyCal = VyInit;
yStop = false;
xStop = false;
onFloor = false;
}
/*---------------------------------------------------*/
// This method holds most of the physics.
// The kinematic equations determine the movement of the
// ball in the gravitational field.
//
// Step the objects in both X,Y.
//
// Reverse inelastically the objects at the walls to
// give movement more realism.
public synchronized void move(double deltaT) {
double dt = 0.0;
double ytmp;
if (xStop && yStop) {
return;
}
// Horizontal movement has no forces except the
// approximation of friction at the walls.
double dx = deltaT * Vx;
double xtmp = x + dx;
if (xtmp < 0.0) {// Left wall
dt = xtmp / Vx;
Vx = Math.abs(Vx) * (1.0 - FrictionLoss);
Vy = Vy * (1.0 - FrictionLoss);
VyCal = VyCal * (1.0 - FrictionLoss);
if (Math.abs(Vx) < Vxstop) {
xStop = true;
Vx = 0.0;
}
if (Math.abs(Vy) < Vystop) {
84
yStop = true;
Vy = 0.0;
VyCal = 0.0;
}
x = dt * Vx;
} else if (xtmp > xRightBound) { // Right wall
dt = (xtmp - xRightBound) / Vx;
Vx = -Math.abs(Vx) * (1 - FrictionLoss);
Vy = Vy * (1.0 - FrictionLoss);
VyCal = VyCal * (1.0 - FrictionLoss);
if (Math.abs(Vx) < Vxstop) {
xStop = true;
Vx = 0.0;
}
if (Math.abs(Vy) < Vystop) {
yStop = true;
Vy = 0.0;
VyCal = 0.0;
}
x = xRightBound + dt * Vx;
} else {
x = xtmp;
}
// Gravitational affects on Y movement
double dy = deltaT * Vy + 0.5 * g * deltaT * deltaT;
double dyCal = deltaT * VyCal + 0.5 * gCal * deltaT * deltaT;
//
System.out.println("increment in y is --- " + y);
// System.out.println("---------------- Displacement: " + dy);
if (!yStop) {
ytmp = y + dy;
} else {
ytmp = yBottomBound;
}
// If this step would put the ball past the floor,
// then must carefully do the rebound.
if (ytmp > yBottomBound) {
if (onFloor) { // 2 times in row on floor so must be at stop
yStop = true;
Vy = 0.0;
VyCal = 0.0;
xStop = true;
} else {
onFloor = true;
// First calculate the time to travel from
// last position to the floor.
85
dy = yBottomBound - y;
// dyCal = yBottomBound - y;
/// System.out.println("++++++++++++Displacement: " + dy);
//
dt = -(Vy / g) + Math.sqrt((Vy * Vy) / (g * g) + (2.0 * dy) / g);
System.out.println("The calculated time: " + dt);
// System.out.println("Time at reach floor instance: " + dt);
Vy += g * dt;// downward velocity exactly at floor
// v = u + at
VyCal += gCal * dt;
// Now reverse the velocity & reduce the speed
// from friction
Vy = -Math.abs(Vy) * (1 - FrictionLoss);
VyCal = -Math.abs(VyCal) * (1.0 - FrictionLoss);
Vx = Vx * (1.0 - FrictionLoss);
if (Math.abs(Vx) < Vxstop) {
xStop = true;
Vx = 0.0;
}
if (Math.abs(Vy) < Vystop) {
yStop = true;
Vy = 0.0;
VyCal = 0.0;
}
}
if (!yStop) {
// Remaining time goes for upward segment
dt = deltaT - dt;
//
System.out.println("remaining time for go upward" + dt);
//
System.out.println("bottom bound: " + yBottomBound);
//
System.out.println("velocity:" + Vy);
//
System.out.println("gravity from box shoot:" + g);
y = yBottomBound + dt * Vy + 0.5 * g * dt * dt;
//
System.out.println("position of y: " + y + "\n");
Vy += g * dt;
// v = u + at
VyCal += gCal * dt;
} else {
y = yBottomBound;
}
} else if (ytmp < 0.0) {
// First calculate the time to travel from
// last position to the ceiling.
dy = y;
dyCal =y;
//System.out.println("//-----------displacement: " + dy);
dt = -(Vy / g) + Math.sqrt((Vy * Vy) / (g * g) + (2.0 * dy) / g);
86
Vy += g * dt;
// v = u + at
VyCal += gCal * dt;
// Now reverse the velocity & reduce the speed
// from friction
Vy = Math.abs(Vy) * (1.0 - FrictionLoss);
VyCal = Math.abs(VyCal) * (1.0 - FrictionLoss);
Vx = Vx * (1.0 - FrictionLoss);
if (Math.abs(Vx) < Vxstop) {
xStop = true;
Vx = 0.0;
}
// Remaining time goes for downward segment
dt = deltaT - dt;
y = dt * Vy + 0.5 * g * dt * dt;
Vy += g * dt;
// v = u + at
VyCal += gCal * dt;
} else {
y = ytmp;
Vy += g * deltaT;
VyCal += gCal * deltaT;
onFloor = false;
}
if (y > yBottomBound) {
y = yBottomBound;
}
drawY = (int) Math.round(y);
drawX = (int) Math.round(x);
}
/*---------------------------------------------------*/
void clipToAffectedArea(Graphics g, int oldx, int oldy, int newx,
int newy, int width, int height) {
int x = Math.min(oldx, newx);
int y = Math.min(oldy, newy);
int w = (Math.max(oldx, newx) + width) - x;
int h = (Math.max(oldy, newy) + height) - y;
g.clipRect(x, y, w, h);
}
/*---------------------------------------------------*/
// Override the base class draw method.
public synchronized void draw(Graphics g) {
lastX = currentX;
lastY = currentY;
currentX = drawX;
currentY = drawY;
87
clipToAffectedArea(g, lastX, lastY, currentX,
currentY, dx, dy);
g.setColor(Color.white);
g.fillRect(0, 0, areaX, areaY);
g.setColor(color);
// Now draw a solid color circle.
g.fillOval(drawX, drawY, dx, dy);
lastX = drawX;
lastY = drawY;
}
public void drawline(Graphics g) {
g.setColor(Color.black);
g.drawLine(15, 15, 15, 340);
g.drawLine(13, 15, 17, 15);
g.drawLine(13, 80, 17, 80);
g.drawLine(13, 145, 17, 145);
g.drawLine(13, 210, 17, 210);
g.drawLine(13, 275, 17, 275);
}
public void label2(Graphics g) {
g.setColor(Color.BLACK);
g.setFont(new Font("TimesRoman", Font.BOLD, 10));
g.drawString("2.0", 2, 20);
g.drawString("1.6", 2, 85);
g.drawString("1.2", 2, 150);
g.drawString("0.8", 2, 215);
g.drawString("0.4", 2, 280);
}
public void label4(Graphics g) {
g.setColor(Color.BLACK);
g.setFont(new Font("TimesRoman", Font.BOLD, 10));
g.drawString("4.0", 2, 20);
g.drawString("3.2", 2, 85);
g.drawString("2.4", 2, 150);
g.drawString("1.6", 2, 215);
g.drawString("0.8", 2, 280);
}
public void label6(Graphics g) {
g.setColor(Color.BLACK);
g.setFont(new Font("TimesRoman", Font.BOLD, 10));
g.drawString("6.0", 2, 20);
g.drawString("4.8", 2, 85);
88
g.drawString("3.6", 2, 150);
g.drawString("2.4", 2, 215);
g.drawString("1.2", 2, 280);
}
public void label8(Graphics g) {
g.setColor(Color.BLACK);
g.setFont(new Font("TimesRoman", Font.BOLD, 10));
g.drawString("8.0", 2, 20);
g.drawString("6.4", 2, 85);
g.drawString("4.8", 2, 150);
g.drawString("3.2", 2, 215);
g.drawString("1.6", 2, 280);
}
public void label10(Graphics g) {
g.setColor(Color.BLACK);
g.setFont(new Font("TimesRoman", Font.BOLD, 10));
g.drawString("10.0", 2, 20);
g.drawString("8.0", 2, 85);
g.drawString("6.0", 2, 150);
g.drawString("4.0", 2, 215);
g.drawString("2.0", 2, 280);
}
}
ObjectToDraw.java
package GravitySimulation;
import java.applet.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import GravitySimulation.*;
/*###################################################*/
// This base class illustrates a simple example
// of inheritance for drawing different shapes.
abstract class ObjectToDraw {
int centerX, centerY; // Center of drawn object
int drawX, drawY; // Origin of object drawing area,
// e.g. top left corner of the
// bounding rectangle.
int dx, dy;
// Width of drawing area.
89
int dyCal;
int areaX, areaY; // Dimensions of the applet
// drawing area.
static Color color;
double Vtot = 0.2;
double Vx, Vy;
double VyCal;
double toggleSign = 1.0;
//---------------------------------public static void getColor(Color c) {
color = c;
}
/*---------------------------------------------------*/
ObjectToDraw(int centerX, int centerY, int dx, int dy,
int dX, int dY) {
this.centerX = centerX;
this.centerY = centerY;
this.dx = dx;
this.dy = dy;
this.dyCal=dy;
//drawX = this.centerX - (dx / 2);
drawX=20;
System.out.println("-----x init is "+drawX);
//drawY = this.centerY - (dy / 2);
drawY=0; //11
System.out.println("-----y init is "+drawY);
areaX = dX;
areaY = dY;
//color = Color.red;
// Initialize the velocity of the object.
Vtot = Vtot * Math.random() + 0.1;
Vx = Vtot * Math.random() + 0.01;
if (Vx >= Vtot) {
Vx = Vtot - 0.2;
}
if (Vx <= 0.05) {
Vx = 0.1;
}
Vy = Math.sqrt(Vtot * Vtot - Vx * Vx);
VyCal = Math.sqrt(Vtot * Vtot - Vx * Vx);
}
/*---------------------------------------------------*/
abstract public void move(double deltaT);
/*---------------------------------------------------*/
// This abstract method will be overridden by the sub-classes
abstract public void draw(Graphics g);
}
90
tutorial.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GravitySimulation;
import GravitySimulation.*;
public class tutorial extends javax.swing.JFrame {
tutorial tut;
/** Creates new form tutorial */
public tutorial() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">
public void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
//
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Tutorial"));
jTextPane1.setEditable(false);
jTextPane1.setText("--------------------------------------\nPhysics Bouncing Ball Simulation\n-------------------------------------\n\n1. Gravitation is a natural phenomenon which gives weight to objects. \n\n2. In an
ideal situation, (neglecting the air resistance) all objects \n dropping from the same height will land at
the same time as the\n gravity pull will cause the same acceleration. \n\n3. The falling of an object body
on earth in general, will be subjected to\n the standard gravitational acceleration (g=9.81ms^-2).\n\n4.
Gravitational acceleration is independent of the mass of the falling object. \n\n5. The difference in the
bounciness of balls is due to:\n a. The elasticity of the ball\n
-The tendency of the object to return
to its equilibrium shape\n b. Law of conservation of energy\n
-Energy can neither be created or
destroyed but can only be\n
changed from one form to another.\n\n6. The formula used in the
calculation involved:\n
a. Velocity\n\tV = u + gt\n\tV^2 = u^2 + 2gs\n
b. Displacement\n\tS = ut
+(gt2)/2\n\n7. Below is the chart for relative bounciness of different types of balls \n\t--------------------------------\n\t| Ball Type \t| %\t|\n\t---------------------------------\n\t| Ping Pong\t| 15\t|\n\t| Baseball\t|
32\t|\n\t| Golf ball\t| 36\t|\n\t| Soccer ball\t| 40\t|\n\t| Tennis ball\t| 49\t|\n\t| Basketball\t|
91
56\t|\n\t| Superball\t| 81\t|\n\t| Metal ball\t| 98\t|\n\t---------------------------------\n\n8. The
comparative gravitational accelerations of planets relative to Earth:\n\n\t--------------------------------\n\t| Body\t| ms^-2 \t|\n\t---------------------------------\n\t| Earth\t| 9.81\t|\n\t| Jupiter\t| 25.93 \t|\n\t|
Mars\t| 3.72 \t|\n\t| Mercury\t| 3.70 \t|\n\t| Moon\t| 1.63 \t|\n\t| Sun\t| 274.1 \t|\n\t| Venus\t| 8.87
\t|\n\t---------------------------------"); // NOI18N
jScrollPane1.setViewportView(jTextPane1);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Lay
out.createSequentialGroup().addContainerGap().addComponent(jScrollPane1,
javax.swing.GroupLayout.DEFAULT_SIZE, 408, Short.MAX_VALUE).addContainerGap()));
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Lay
out.createSequentialGroup().addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,
478,
javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)));
jLabel1.setFont(new java.awt.Font("Calibri", 1, 24));
jLabel1.setText("Physics Simulator: Gravity");
jLabel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jButton1.setText("Close");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
// tut.exit();
setVisible(false);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSeque
ntialGroup().addGap(83, 83, 83).addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE,
275,
javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap(102,
Short.MAX_VALUE)).addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup().addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE).addComponent(jPanel1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap()).addGroup(layout.createSequentialGrou
p().addGap(189, 189, 189).addComponent(jButton1).addContainerGap(212, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(javax.swing.GroupL
ayout.Alignment.TRAILING, layout.createSequentialGroup().addContainerGap().addComponent(jLabel1,
92
javax.swing.GroupLayout.DEFAULT_SIZE,
57,
Short.MAX_VALUE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addCo
mponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE).addGap(15,
15,
15).addComponent(jButton1).addContainerGap()));
pack();
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration
}
93
Related documents