# Thread: Challenge: calculating velocity of a moving rectangle

1. Member Join Date
Apr 2012
Posts
4
Rep Power
0

## Challenge: calculating velocity of a moving rectangle

I am working on a (HUGE) simulation project and have been stuck on a part that requires me to know the motion dynamics of a moving object. On clicking the "transmit" button a bunch of "packets" travel downward. I need to know the velocity of the packets (or just a packet). The way I did it was by calculating the distance (pixels converted to meters) between two points on the panel, and dividing that distance by the time it takes for the packet (left most) to travel from one point to another. I, however, get huge discrepancies in the calculated time, and, consequently, in the resulting velocity. Is there an alternative to this approach. Better yet, can I improve this approach. Thanks a bunch.

PS: The code is just too long, but I will post it anyway
XML Code:
```import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.Timer;
import javax.swing.*;

public class Driver{

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

private static void createAndShowGUI() {
System.out.println("Created GUI on EDT? "+
JFrame f = new JFrame("Simulation Project");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Creating a left-positioned panel for the labels
JPanel panelleft = new JPanel();
panelleft.setBackground(Color.WHITE);
panelleft.setBorder(BorderFactory.createMatteBorder(2,2,2,0,Color.BLACK));

JLabel label = new JLabel("             Sender");
//For positioning the Sender label purposes
JLabel label2 = new JLabel(" ");
JLabel label3 = new JLabel(" ");
JLabel label4 = new JLabel(" ");
JLabel label5 = new JLabel(" ");
JLabel label6 = new JLabel(" ");
JLabel label7 = new JLabel(" ");
JLabel label8 = new JLabel(" ");
JLabel label9 = new JLabel(" ");
JLabel label10 = new JLabel(" ");
JLabel label11 = new JLabel(" ");
JLabel label12 = new JLabel(" ");
JLabel label13 = new JLabel(" ");
JLabel label15 = new JLabel(" ");
JLabel label16 = new JLabel(" ");
JLabel label17 = new JLabel(" ");
JLabel label18 = new JLabel(" ");
JLabel label14 = new JLabel("            Reciever");
label.setFont(new Font("Ariel", 2, 14));
label14.setFont(new Font("Ariel", 2, 14));
//Making sure the labels are on top of each other
//...and not side by side
panelleft.setLayout(new BoxLayout(panelleft, BoxLayout.Y_AXIS));

f.setSize(450,550);
f.setLocationRelativeTo(f);
f.setVisible(true);
}
}
class MyPanel extends JPanel implements ActionListener{
int delay = 100;
Timer t = new Timer(delay, this);
Timer t2 = new Timer(delay, this);
JTextField field = new JTextField(10);

private int squareX = 50;
private int squareY = 50;
private int squareW = 20;
private int squareH = 26;
int xCordinate;
int yCordinate;
int yOffset;
int x = 10;
int y = 70;
int y2 = 251;
long t0;
long t1;
long netTime;
double time_seconds;
double displacement;
double velocity = .0068;
boolean drawRectangle = false;
boolean ackRectangle = false;
boolean killIntention = false;
boolean registerOnce = false;
JButton button = new JButton("Transmit");

public MyPanel() {
setBackground(Color.WHITE);
//MatteBorder signifies the border width for every side
setBorder(BorderFactory.createMatteBorder(2,0,2,2,Color.BLACK));

button.setPreferredSize(new Dimension(100,25));
button.setBackground(Color.LIGHT_GRAY);
button.setFont(new Font("Ariel", 2, 15));

//velocity of the moving rectangle comes out to be .006 m/s
//upper bound for velocity = .0068 m/s
public void mousePressed(MouseEvent e) {
t1 = System.currentTimeMillis();
killIntention = true;
xCordinate = e.getX();					//given the elapsed time, would it be at that position
yCordinate = e.getY();
calculateCordinate();
calculateDiff();
timeinSeconds();
multiplyFunction();
//calculateVelocity();
field.setText("this " + netTime);
}
});

//   public void mouseDragged(MouseEvent e) {
// moveSquare(e.getX(),e.getY());
//}
// });

}//contructor

public void actionPerformed(ActionEvent e){
if(registerOnce == false){				//Keeping the initial time fixed
t0 = System.currentTimeMillis();
}
registerOnce = true;
drawRectangle = true;

if(ackRectangle){
if(y < 71){
y = 70;
}
else{
y = y - 2;
}
}
else
{

if(y > 250){
y = 251;
}
else
{
y = y + 2;
}
}
repaint();
}

public Dimension getPreferredSize() {
return new Dimension(250,200);
}
void calculateDiff(){
netTime = t1 - t0;
//netTime = netTime/1000;
}
void calculateCordinate(){
yOffset = yCordinate - 87;
}
void timeinSeconds(){
time_seconds = netTime/1000;
}

void multiplyFunction(){
displacement = velocity * time_seconds;
}
public void paintComponent(Graphics g) {

super.paintComponent(g);

//Draw Static Rectangles. TOP
g.setColor(Color.BLACK);
g.fillRect(10,70,8,17);
g.fillRect(60,70,28,57);
g.fillRect(109,70,28,57);
g.fillRect(158,70,28,57);
g.fillRect(207,70,28,57);

//Draw Static Rectangles. BOTTOM
g.drawRect(10,251,8,17);
g.drawRect(60,251,28,57);
g.drawRect(109,251,28,57);
g.drawRect(158,251,28,57);
g.drawRect(207,251,28,57);
///////////////////////////////////////////////////////////
//**********************************//
//////////////////////////////////////
//Dynamic rectangles

//Move Rectangles
//ackRectangle = true;
g.setColor(Color.RED);
g.fillRect(10, 251, 8, 17);
g.fillRect(60, 251, 28, 57);
g.fillRect(109, 251, 28, 57);
g.fillRect(158, 251, 28, 57);
g.fillRect(207, 251, 28, 57);
ackRectangle = true;

}
else if(ackRectangle){
g.setColor(Color.RED);
g.fillRect(10, 251, 8, 17);
g.fillRect(60, 251, 28, 57);
g.fillRect(109, 251, 28, 57);
g.fillRect(158, 251, 28, 57);
g.fillRect(207, 251, 28, 57);
g.setColor(Color.YELLOW);
g.fillRect(10, y, 8, 17);
g.fillRect(60, y, 28, 57);
g.fillRect(109, y, 28, 57);
g.fillRect(158, y, 28, 57);
g.fillRect(207, y, 28, 57);
g.setColor(Color.BLUE);
g.fillRect(10, 70, 8, 17);
g.fillRect(60, 70, 28, 57);
g.fillRect(109, 70, 28, 57);
g.fillRect(158, 70, 28, 57);
g.fillRect(207, 70, 28, 57);
}
// t2.start();
}

else if(drawRectangle){
if(killIntention && xCordinate >= 10 && xCordinate <= 37){
g.setColor(Color.WHITE);
g.fillRect(10, y, 8,17);
}
else{
g.setColor(Color.cyan);
g.fillRect(10, y, 8,17);
}
g.setColor(Color.CYAN);
g.fillRect(60,y,28,57);
g.fillRect(109,y,28,57);
g.fillRect(158,y,28,57);
g.fillRect(207,y, 28,57);
t.start();
}

}
}```  Reply With Quote

2. ## Re: Challenge: calculating velocity of a moving rectangle

Regardless of how you write your program, essentially you have a GUI which is nothing more than a visual display of some process, and you have the logic behind that process (here the changing distance value of some object). I suggest a re-organization of your program to separate out concerns. For example,
• Create a Packet class that represents the logical information needed for a Packet including (perhaps) its size and position, and getters and setters so that you can get and set or advance its position. To improve accuracy, the position should probably be held by double fields. Packet may even check system time so as to be able to give speed information, or this may be done by other objects that "drive" the Packets.
• Create a PacketCollection class that holds all your Packets together in perhaps an ArrayList of Packets or ArrayList<Packet>.
• Create a Model class that holds all the above plus the logic to move the packets, to get their position, and perhaps to check system time intervals and get speed.
• None of the classes above would contain a drop of GUI code. Many of the classes above would have code to allow other classes to listen to them (I have usually used a PropertyChangeSupport or SwingPropertyChangeSupport object for this) as well as methods that allow adding and removing listeners.
• Then create your GUI classes that listen to the model and passively draw the position of the models.
• You can also add listeners to monitor the speed of the Packets if desired.

As an aside, your code above has a *lot* of redundant code, code that can be greatly simplified by using arrays or collections.  Reply With Quote

3. Member Join Date
Apr 2012
Posts
4
Rep Power
0

## Re: Challenge: calculating velocity of a moving rectangle

Thank you so much for your reply. Yes, I do believe that my code is substandard. This, however, is the first phase. The second phase would appropriately perform a clean-up that would render the program much more standard. For the current phase I am implementing operations (like velocity calculation) that would comprise the "heart" of the program without paying too much attention to the right way of doing things (for now).  Reply With Quote

4. ## Re: Challenge: calculating velocity of a moving rectangle Originally Posted by vasiqshair Thank you so much for your reply. Yes, I do believe that my code is substandard. This, however, is the first phase. The second phase would appropriately perform a clean-up that would render the program much more standard. For the current phase I am implementing operations (like velocity calculation) that would comprise the "heart" of the program without paying too much attention to the right way of doing things (for now).
I personally think that this is a backwards way to code. You're better off creating your separate objects now. Else you'll be trying to do bad things like base your velocity calculations on the GUI portion of the code rather than the model.  Reply With Quote

5. ## Re: Challenge: calculating velocity of a moving rectangle

db  Reply With Quote

6. Member Join Date
Apr 2012
Posts
4
Rep Power
0

## Re: Challenge: calculating velocity of a moving rectangle

Fubarable, thank you for your input. Yes, packet class definitely sounds like a good idea. I will start on it and I will keep updating the thread  Reply With Quote

animation, graphics, java, rectangle, velocity 