Little tips: Using Java to simulate small balls for parabolic motion

Source: Internet
Author: User

These days just learned the Java thread, then followed the book to do a few threads of practice, one of the exercises is the small ball moving up. This belief is simple, as long as the use of threading can easily be achieved. And then saw it after a lesson study questions, how to make a parabolic motion of the ball, which I debugging for a long time, the internet also found a lot of information, but there is no kind of suitable for our small white tutorial, so I simply talk about my ideas. I will start with how to draw a small ball to achieve the parabolic motion. Hey!!

First, the task decomposition

Now let's do the parabolic motion of the small ball, first of all do not hurry to write code, first to imagine the good results are what it looks like. I divided the task into three steps, the first step, draw a small ball, the second step, how to move the small ball, the third step, let the ball do parabolic motion.

Two, draw a small ball

This is a relatively difficult task for you to believe. I'll simply mention it here. Here I'm using the Java Swing component. First, I'll attach the code.

1  PackageStar;2 3 ImportJava.awt.Color;4 ImportJava.awt.Graphics;5 6 ImportJavax.swing.JFrame;7 ImportJavax.swing.JPanel;8 9  Public classTest1 {Ten  One     /** A      * @paramargs -      */ -      Public Static voidMain (string[] args) { the         //TODO auto-generated Method Stub -JFrame W =NewJFrame ();//Build Window Container Object -MyPanel3 PW =NewMyPanel3 ();//Create an extended canvas object, when the canvas already has a small ball -W.add (PW);//Add the canvas to the window container +W.setsize (400,500);//Set Window Size -W.setvisible (true);//The above window is in memory and is not displayed +     } A  at } - classMyPanel3extendsjpanel{//expand to the canvas you want by inheriting the canvas class -     intx=30;//define the initial horizontal axis of the ball -     inty=30;//defining the ball's initial ordinate -      Public voidPaint (Graphics g) {//override the Paint method, where g is equivalent to the brush role -      inG.setcolor (NewColor (30,34,255));//Set Brush Color -          toG.filloval (x,y,20,20);//draw a circle with a diameter of 20 +     } -}

Because you can not draw directly in the window container, so you can only find an intermediary, the intermediary is the canvas, the first thing you want to draw on the canvas, and then the canvas through the Add method added to the window container. Then Java provides our canvas as an empty canvas, where I'm going to rewrite the paint method by inheriting the canvas class, so that the canvas has what I want. With 27 lines of ~32 line code, a small ball has been drawn on the canvas.

Three, let the small ball move up

Now, the ball is already there, then let the ball move, we first let the ball fall vertically. This can be said to let the ball move is not simple, the use of circulation constantly let the ball's vertical axis add a not good, like this,

 public  void  paint (Graphics g) {//  Overriding the Paint method, where g is equivalent to the brush role    G.setcolor ( new  color (30,34,255)); //  set brush color  while
     (true   if  (y>400) {//  More than 400 stop motion  break             ; } g.filloval (x, Y,  20, 20); //         y++; }    }

But is it really what we think it is? Well, I'm not suspense, his real running results are like this.

This result is in fact expected, because our coordinates are added, but the previous painting did not erase it!! Smart you should also think of as long as found to erase the previous painting, the ball does not move up. Here is the use of threading knowledge, attached here attached to the key source of the ball moving up

1 classMyPanel2extendsJPanelImplementsrunnable{//4     intX=30;5     intY=30;6    8      Public voidPaint (Graphics g) {9        Super.paint (g);//Erase the last draw of the ballTenG.setcolor (NewColor (30,34,255)); One          AG.filloval (x,y,20,20); -     } -      Public voidRun () {//implements the Run method in the Runable interface and automatically calls the Run method when the thread starts.  the          while(true){ - +y++;//coordinates per 100ms plus one coordinate -             Try{ +Thread.Sleep (100);} Thread breaks every 100ms A             Catch(Exception e) {}; at repaint ();//Call the Paint method again -         } -}

Here the Nineth line of code to focus on, if the deletion of this code, the final result is similar to the use of loops, did not erase the previous painting. Because you want to use a thread, create the thread object in the main function and let him start.

Thread t = new thread (PW);
T.start ();

Four, let the ball do parabolic motion

OK, step into the final point, let the ball do parabolic motion. Before we begin here, let's start with a high school physics free fall, which is not a parabolic form, right, the free fall horizontal direction is not to do uniform motion, the vertical direction is not to do acceleration for G accelerated motion. Have you ever been inspired here? Well, I'm not suspense either. Listen to me slowly, in the above we move the essence is to let the ball in each fixed time is every 100ms time, the ball's ordinate +1; the horizontal direction of the parabola is not a fixed value in the horizontal coordinates of each fixed time period. For example, the horizontal direction is 1 pixels per 100ms. Similarly, to analyze the vertical direction of the situation. I don't know if you remember one of the rules of accelerated motion: in the acceleration movement with the initial velocity zero, the displacement ratio of the same time period is 1:3:5:7 ...; The meaning is that in the first 100ms time, increase or decrease 1 pixels, then the second 100ms time period of 3 pixels, the third 100ms increase of 5 pixels ... In turn, the code is attached here

1 classMyPanel2extendsJPanelImplementsrunnable{2     3     intX=30;4     intY=30;5   int num=1;//Record the y-coordinate increment of pixel value per 100ms6      Public voidPaint (Graphics g) {7         Super. Paint (g);8G.setcolor (NewColor (30,34,255));9         TenG.filloval (x,y,20,20); One     } A      Public voidrun () { -          while(true){ -X+=4; they+=num; -                num+=2;//per 100ms his increment plus 2 -                  -             Try{ +Thread.Sleep (100);} -             Catch(Exception e) {}; + repaint (); A         } at     } -}

It's done here.

V. Concluding remarks Through this exercise, let me clearly realize that learning programming is not just to learn programming, but need a multi-faceted knowledge of the link, each programming people have their own set of methodologies in programming, and these methodologies are not produced in thin air, but through a lot of knowledge of the precipitate, and then produce qualitative change. I hope we can find out what you want on the road of programming.

Little tips: Using Java to simulate small balls for parabolic motion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.