Results 1 to 6 of 6
Like Tree1Likes
  • 1 Post By vasiqshair

Thread: Challenge: calculating velocity of a moving rectangle

  1. #1
    vasiqshair is offline Member
    Join Date
    Apr 2012
    Posts
    4
    Rep Power
    0

    Default 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.MouseAdapter;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.MouseMotionAdapter;
    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? "+
            SwingUtilities.isEventDispatchThread());
            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));
            panelleft.add(label2);
            panelleft.add(label3);
         //   panelleft.add(label4);
            panelleft.add(label5);
            panelleft.add(label6);
            panelleft.add(label7);
            panelleft.add(label);
            panelleft.add(label8);
            panelleft.add(label9);
            panelleft.add(label10);
            panelleft.add(label11);
            panelleft.add(label12);
            panelleft.add(label13);
            panelleft.add(label15);
            panelleft.add(label16);
            panelleft.add(label17);
            panelleft.add(label18);
            panelleft.add(label14);
            
            f.add(panelleft, BorderLayout.WEST);
            f.add(new MyPanel(), BorderLayout.CENTER);
            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 receiverRectangle = false;
        boolean ackRectangle = false;
        boolean ackReceived = 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));
            add(button);
            add(field);
            
            button.addActionListener(this);
            //velocity of the moving rectangle comes out to be .006 m/s
            //upper bound for velocity = .0068 m/s
            addMouseListener(new MouseAdapter() {			//for later
                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);
                }
            });
    
           // addMouseMotionListener(new MouseAdapter() {		// for later
             //   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;
        			ackReceived = true;
        		}
        		else{	
        		y = y - 2;
        		}
        	}
        	else
        	{
        	
        	if(y > 250){
        		receiverRectangle = true;
        		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
        	 if(receiverRectangle){
        		 //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;
        		 receiverRectangle = false;
        		 
        	 }
        	 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);
        		 if(ackReceived){
        			 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();
        }  
        	 
        	
    }
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default 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.

  3. #3
    vasiqshair is offline Member
    Join Date
    Apr 2012
    Posts
    4
    Rep Power
    0

    Default 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).

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Challenge: calculating velocity of a moving rectangle

    Quote Originally Posted by vasiqshair View Post
    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.

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,415
    Rep Power
    20

    Default Re: Challenge: calculating velocity of a moving rectangle

    Nothing advanced about this. Moving to New to Java.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  6. #6
    vasiqshair is offline Member
    Join Date
    Apr 2012
    Posts
    4
    Rep Power
    0

    Default 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
    Fubarable likes this.

Similar Threads

  1. Can anyone help me with this moving rectangle?
    By mdCollins1 in forum New To Java
    Replies: 7
    Last Post: 04-17-2012, 03:09 AM
  2. Moving a rectangle with a button click
    By vasiqshair in forum Advanced Java
    Replies: 6
    Last Post: 04-15-2012, 12:03 PM
  3. calculating the speed of moving point
    By gedas in forum Java 2D
    Replies: 14
    Last Post: 03-17-2011, 03:29 PM
  4. calculating the speed of moving point
    By gedas in forum New To Java
    Replies: 0
    Last Post: 03-16-2011, 05:45 PM
  5. Wrong with Rectangle res = new Rectangle(0,0,0,0);???
    By jiapei100 in forum AWT / Swing
    Replies: 3
    Last Post: 09-25-2010, 03:39 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •