简体   繁体   中英

Using Dr.Java, want to know how to make an item bounce

So I have a program that I'm trying to create for a class, and I need to create a country scene with a farm and a sun. The sun has to bounce up and down. The current problem I'm facing is that the sun keeps going down, and won't bounce up. Here is my code:

import javax.swing.*;
import java.awt.*;
/**
 * Date: Oct 14, 2016
 * Author: 
 * Description: Shows a country side with a farm and a sun bouncing up and down.
 */
public class WeAreInThePictures extends JFrame
{
  ImageIcon sun, farm, bG; //assigns sun, farm and background to an image variable
  static int x = 0, y = -50; //starting position of the sun
  static int ySpeed = 10; //speed in y direction
  static double delay = 1.0;


  public WeAreInThePictures() { 
    super ("We Are In The Pictures!");
    setSize (852, 480);
    bG = new ImageIcon ("1.jpg");
    sun = new ImageIcon ("sun.png");
    farm = new ImageIcon ("farm.png");
setVisible (true);
  }

  public static void main(String[] args) { 
    new WeAreInThePictures ();
  }

  public void paint (Graphics g)
  {
    for (int i = 0; i < 1000; i++)
{
  bG.paintIcon (this, g, 0, 0);
  farm.paintIcon (this, g, 500, 50);

  y = y + ySpeed;
  if (ySpeed > 0)
  {
    sun.paintIcon (this, g, x, y);

    for (int j = 0; j < 550000; j++) 
    {
      delay = Math.pow (delay, 1);
    }
  }
  else if (y > 50)
  {
    ySpeed = ySpeed - 1;
  }
  else if (y <= 0)
   {
     ySpeed = ySpeed - 1;
   }
  }
 }
}

Can someone explain to me what is wrong, how i should fix it and why the problem is occurring?

Your problem is that you appear to have written this code without looking at any Swing Graphics tutorial or similar question on this site regarding Swing animation (why?). You're drawing directly in the JFrame, something that you shouldn't be doing, you've got object mutation code within a paint method, again something that you shouldn't be doing.

Instead do as you recommended in the tutorials, and most any other similar question on this site, in fact, search the problem before asking:

  • Draw in the paintComponent method of a JPanel that is displayed in a JFrame.
  • Use a Swing Timer for your animation loop
  • Change the speed's direction in the timer's ActionListener, not in a paintComponent method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM