【问题标题】:Implement multiple bouncing balls实现多个弹跳球
【发布时间】:2013-11-20 16:57:36
【问题描述】:

我对 Java 有一点了解,我决定参加一门课程来学习更多知识,并且我被分配了一个相当简单的任务。我已经完成了大部分工作,我知道剩下的事情一定很简单,但我似乎无法完全理解。到目前为止,我已经能够成功创建一个有 1 个弹跳球的程序,但我现在想允许用户输入要弹跳的球的数量。我在 Ball 类中尝试了几个不同的循环,但它们都不起作用。有人愿意快速伸出援手吗?我几乎可以肯定它需要一个 Array 或 ArrayList 并将球存储在其中,但我还没有找到一个可行的解决方案。我在网站上查看过类似的其他问题,但没有一个能完全解决我的问题。如果您能提供帮助,谢谢!

主类:

public class mainClass {

    /**
    /**
   * Frame to hold a bouncing ball panel, implemented in the BallPanel class.
   * Controls the animation of the ball via pauses and calls to BallPanel's move
   * method.
   *
   * @author Michael Peterson modified by Mr O Aug 2012
   */
  public static class BallTest extends JFrame {

    // size of the window
    private static final int WINDOW_WIDTH = 500;
    private static final int WINDOW_HEIGHT = 300;
    // panel containing the bouncing ball
    private BallPanel ballPanel;

    /**
     * Pause command used to control the speed of the bouncing ball animation.
     * Currently pauses for 20 ms. Use smaller values for faster animation and
     * vice versa.
     */
    public static void pause() {
      try {
        Thread.sleep(20); // pause for 20 ms
      } catch (Exception e) {
        System.out.println(e);
        e.printStackTrace();
      }//end of catch
    }//end of pause method 

    /**
     * Creates a new instance of BallTest
     */
    public BallTest() {
      super("Bouncing Ball");  // set frame name
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
      setLayout(new BorderLayout());
      ballPanel = new BallPanel();

      add(ballPanel);
      center(this);
      setVisible(true);

      // infinite animation loop, program halts when window is closed.
      while (true) {
        pause();
        ballPanel.move(ballPanel);
      }//end of while loop of animation        
    } //end of BallTest Constructor 

    /**
     * Helper routine to center a frame on the screen (will cause problems if
     * frame is bigger than the screen!)
     */
    public static void center(JFrame frame) {
      GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
      Point center = ge.getCenterPoint();

      int w = frame.getWidth();
      int h = frame.getHeight();

      int x = center.x - w / 2, y = center.y - h / 2;
      frame.setBounds(x, y, w, h);
      frame.validate();
    }//end of center method  
  }//end of BallPanel Class

  public static void main(String[] args) {
    BallTest t = new BallTest(); //make a BallTest object
  }//end of main method
}//end of Fall2012Lab11StarterCode class

球类:

public  class  Ball extends JPanel  {

  private int bxCoord;        //the ball's x coordinate
  private int byCoord;        //the ball's y coordinate
  private int bHeight;        //the ball's height
  private int bWidth;         //the ball's weight
  private int bRise;          //the ball's y change
  private int bRun;           //the ball's x change
  private Color bColor;       //the ball's color

//Constructor
  public Ball() {
    bxCoord = setStartBxCoord();
    byCoord = setStartByCoord();
    bHeight = setStartBHeight();
    bWidth = setStartBWidth();
    bRise = setStartBRise();
    bRun = setStartBRun();
    bColor = setStartColor();
  }

/**
 * The setters, getters, and initial value for the ball's x coordinate 
 */
  public void setBxCoord(int xCoord) {
    bxCoord = xCoord;
  }

  public int setStartBxCoord() {
    int xCoord;
    xCoord = (int) (Math.random() * 51);
    return xCoord;
  }

  public int getBxCoord() {
    return bxCoord;
  }

  /**
 * The setters, getters, and initial value for the ball's y coordinate 
 */
  public void setByCoord(int yCoord) {
    bxCoord = yCoord;
  }

  public int setStartByCoord() {
    int yCoord;
    yCoord = (int) (Math.random() * 51);
    return yCoord;
  }

  public int getByCoord() {
    return byCoord;
  }

  /**
 * The setters, getters, and initial value for the ball's x height 
 */
  public void setBHeight(int height) {
    bHeight = height;
  }

  public int setStartBHeight() {
    int height;
    height = (int) (10 + Math.random() * 11);
    return height;
  }

  public int getBHeight() {
    return bHeight;
  }

  public void setBWidth(int width) {
    bWidth = width;
  }

  /**
 * The setters, getters, and initial value for the ball's x width 
 */
  public int setStartBWidth() {
    int width;
    width = (int) (10 + Math.random() * 11);
    return width;
  }

  public int getBWidth() {
    return bWidth;
  }

  /**
 * The setters, getters, and initial value for the ball's rise 
 */
  public void setBRise(int rise) {
    bRise = rise;
  }

  public int setStartBRise() {
    int rise;
    rise = (int) (Math.random() * 11);
    return rise;
  }

  public int getBRise() {
    return bRise;
  }

  /**
 * The setters, getters, and initial value for the ball's run 
 */
  public void setBRun(int run) {
    bRun = run;
  }

  public int setStartBRun() {
    int run;
    run = (int) (Math.random() * 11);
    return run;
  }

  public int getBRun() {
    return bRun;
  }

  /**
   * The movement of the ball in the x and y direction
   */
  public void moveX(){

    bxCoord += bRun;    
  }

  public void moveY(){
    byCoord +=   bRise;
  }

 /**
 * The setters, getters, and initial value for the ball's color 
 */
  public void setColor(Color color) {
    bColor = color;
  }

  public Color setStartColor() {
    int red = (int) (Math.random() * 256);
    int green = (int) (Math.random() * 256);
    int blue = (int) (Math.random() * 256);
    Color ranColor = new Color(red, green, blue);
    return ranColor;
  }

  public Color getbColor() {
    return bColor;
  }
    /**
   * Computes the next position for the balls and updates their positions.
   */
    public void move(BallPanel ballPanel) {
    // If ball is approaching a wall, reverse direction
    if ((getBxCoord() < (0  - getBRun())) || (getBxCoord() > (ballPanel.getWidth() - getBWidth()))) {
      setBRun(-getBRun());
    }
    if ((getByCoord() < (0 - getBRise())) || (getByCoord() > (ballPanel.getHeight() - getBHeight()))) {
      setBRise(-getBRise());
    }
    // "Move" ball according to values in rise and run
    moveX();
    moveY();
  } // end method move
}//end of Ball Class

球面板类:

public class BallPanel extends JPanel {

  Ball ball = new Ball();  //creat a ball.

  /**
   * Creates a new instance of BallPanel
   */
  public BallPanel() {
    super();
  }
/**
 * The move method moves the ball and repaints the panel
 * PreCondtion: A panel containing a ball has been created
 * PostCondition: The position of a ball on the panel has moved.  The panell
 * is repainted with the ball in the new position.
 * @param ballPanel The name of the panel on which the ball is found
 */
  public void move(BallPanel ballPanel) {
    ball.move(ballPanel);
    repaint();
  }

 /**
  * Paints the balls at their current positions within the panel.
  * PreCondition: A graphics object has been created and needs to be displayed 
  * PostCondition: The graphics object g has been displayed
  * @param g The graphic object to be displayed
  */
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
       g.setColor(Color.black);                         // set color black
    g.fillRect(0, 0, getWidth(), getHeight()); // paint background
    // Paint the Ball
    g.setColor(ball.getbColor());
    g.fillOval(ball.getBxCoord(), ball.getByCoord(),
            ball.getBWidth(), ball.getBHeight());
  }//end of paintComponent method
}//end of BallPanel class

【问题讨论】:

    标签: java arrays arraylist


    【解决方案1】:

    好吧,我纯粹是根据我以前做过的类似代码来回答你的,因为我没有时间测试你的代码。

    你的 ballPanel 类应该看起来更像这样:

    import java.util.ArrayList;
    public class BallPanel extends JPanel{
        private ArrayList<Ball> BallList = new ArrayList<Ball>();
        private int num;
        public BallPanel(int numberOfBalls){
            super();
            num = numberOfBalls;
            for(int i = 0; i<num; i++){BallList.add(new Ball());}
        }
    
        //the rest of your methods, using for loops for the balls
    

    另外我认为你可以使用它来代替 ArrayList(这更容易):

    Ball[] BallList = new Ball[numberOfBalls];
    

    那么移动方法的示例应该如下所示:

    public void move(BallPanel ballPanel){
        for(int i = 0; i<num; i++){
            BallList[i].move(ballPanel);
        }
        repaint();
    }
    

    【讨论】:

      【解决方案2】:

      我在弹跳球程序中遇到了类似的问题。尝试了之前发布的代码,但 public void move(BallPanel 区域不起作用。当我访问该位置的数组时,球停止移动。这是我当前的移动代码:

      public void move(BallPanel ballPanel, ArrayList<Ball> ballList) {
      
        for(int i = 0; i<1; i++){
            System.out.println("mmm" + i);
            ballList.get(i).move(ballPanel);
        }
      
        repaint();
      

      其次如上图的paintComponent区域,只有ball用于绘制球。是否可以多次调用paintComponent 但其中只有一个变量球。该部分如下所示:

      public void paintComponent(Graphics g) {
         super.paintComponent(g);
         g.setColor(Color.black);                         // set color black
         g.fillRect(0, 0, getWidth(), getHeight()); // paint background
      
      // Paint the Ball
         g.setColor(ball.getbColor());
         g.fillOval(ball.getBxCoord(), ball.getByCoord(),
              ball.getBWidth(), ball.getBHeight());
      

      【讨论】:

      • 这如何回答这个问题?
      猜你喜欢
      • 1970-01-01
      • 2013-01-13
      • 2013-05-23
      • 2020-02-22
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 2012-10-12
      相关资源
      最近更新 更多