2013-11-20 3 views
0

Я немного перепутал с Java, и я решил пройти курс, чтобы узнать еще кое-что, и мне было назначено довольно простое задание. У меня это в основном сделано, и я знаю, что осталось, должно быть просто, но я не могу, похоже, получить его. До сих пор мне удалось успешно создать программу, в которой есть один прыгающий мяч, но теперь я хотел бы позволить пользователю вводить количество шаров для отскока. Я пробовал несколько разных циклов в классе 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 

ответ

0

Ну я отвечать вам исключительно на предыдущих кодах я сделал похож на это, потому что у меня не было времени проверить ваши.

Ваш класс 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(); 
} 
-1

У меня были похожие проблемы с Bouncing Ball progr есть. .. Пробовал ранее отвечал код, но общественное движение недействительным (область 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 выше, только мяч используется для рисования мяча это нормально, что 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()); 
+0

Как этот ответ вопрос ? – AymenDaoudi

Смежные вопросы