简体   繁体   English

使用 Dr.Java,想知道如何让项目反弹

[英]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?).您的问题是您似乎在没有查看任何 Swing 图形教程或本网站上有关 Swing 动画的类似问题的情况下编写了此代码(为什么?)。 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.您直接在 JFrame 中绘图,这是您不应该做的事情,您在 Paint 方法中有对象突变代码,这又是您不应该做的事情。

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.在 JFrame 中显示的 JPanel 的paintComponent 方法中绘制。
  • Use a Swing Timer for your animation loop为您的动画循环使用 Swing Timer
  • Change the speed's direction in the timer's ActionListener, not in a paintComponent method.在计时器的 ActionListener 中更改速度方向,而不是在paintComponent 方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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