1

我想在java中做一个弹跳球应用程序。每个球都应该通过鼠标点击发生,每个球都应该有随机的速度、颜色、半径和起始位置。除了发生鼠标侦听器的部分之外,我设法做了所有事情。无论我在 mousePressed 方法中做什么都不起作用。我应该怎么做才能让用户在按下鼠标时创建一个随机球?

编辑:这是我的代码的最后一个版本。现在的问题是我不能创造一个以上的球。当我点击屏幕时,同一个球只是保持超速。

弹跳球类

public class BouncingBalls extends JPanel implements MouseListener{

private Ball ball;
protected List<Ball> balls = new ArrayList<Ball>(20);
private Container container;
private DrawCanvas canvas;
private int canvasWidth;
private int canvasHeight;
public static final int UPDATE_RATE = 30;

int x = random(480);
int y = random(480);
int speedX = random(30);
int speedY = random(30);
int radius = random(20);
int red = random(255);
int green = random(255);
int blue = random(255);
int count = 0;

public static int random(int maxRange) {
    return (int) Math.round((Math.random() * maxRange));
}

public BouncingBalls(int width, int height){

    canvasWidth = width;
    canvasHeight = height;

    ball = new Ball(x, y, speedX, speedY, radius, red, green, blue);
    container = new Container();

    canvas = new DrawCanvas();
    this.setLayout(new BorderLayout());
    this.add(canvas, BorderLayout.CENTER);
    this.addMouseListener(this);

}

public void start(){

    Thread t = new Thread(){

        public void run(){

            while(true){

                update();
                repaint();
                try {
                    Thread.sleep(1000 / UPDATE_RATE);
                } catch (InterruptedException e) {}
            }
        }
    };
    t.start();
}

public void update(){

    ball.move(container);
}

class DrawCanvas extends JPanel{

    public void paintComponent(Graphics g){

        super.paintComponent(g);
        container.draw(g);
        ball.draw(g);
    }

    public Dimension getPreferredSize(){

        return(new Dimension(canvasWidth, canvasHeight));
    }
}

public static void main(String[] args){

    javax.swing.SwingUtilities.invokeLater(new Runnable(){

        public void run(){

            JFrame f = new JFrame("Bouncing Balls");
            f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
            f.setContentPane(new BouncingBalls(500, 500));
            f.pack();
            f.setVisible(true);
        }
    });
}

@Override
public void mouseClicked(MouseEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void mouseEntered(MouseEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent e) {

    balls.add(new Ball(x, y, speedX, speedY, radius, red, green, blue));
    start();
}

@Override
public void mouseReleased(MouseEvent e) {
    // TODO Auto-generated method stub

}
}

球类

import java.awt.Color;
import java.awt.Graphics;

public class Ball{

public static int random(int maxRange) {
    return (int) Math.round((Math.random() * maxRange));
}

private BouncingBalls balls;
int x = random(480);
int y = random(480);
int speedX = random(30);
int speedY = random(30);
int radius = random(20);
int red = random(255);
int green = random(255);
int blue = random(255);
int i = 0;

public Ball(int x, int y, int speedX, int speedY, int radius, int red, int green, int blue){

    this.x = x;
    this.y = y;
    this.speedX = speedX;
    this.speedY = speedY;
    this.radius = radius;
    this.red = red;
    this.green = green;
    this.blue = blue;
}

public void draw(Graphics g){

    for(Ball ball : balls){

        g.setColor(new Color(red, green, blue));
        g.fillOval((int)(x - radius), (int)(y - radius), (int)(2 * radius), (int)(2 * radius));
    }
}

public void move(Container container){

    x += speedX;
    y += speedY;

    if(x - radius < 0){

        speedX = -speedX;
        x = radius;
    }
    else if(x + radius > 500){

        speedX = -speedX;
        x = 500 - radius;
    }

    if(y - radius < 0){

        speedY = -speedY;
        y = radius;
    }
    else if(y + radius > 500){

        speedY = -speedY;
        y = 500 - radius;
    }
}
}

容器类

import java.awt.Color;
import java.awt.Graphics;

public class Container {

private static final int HEIGHT = 500;
private static final int WIDTH = 500;
private static final Color COLOR = Color.WHITE;

public void draw(Graphics g){

    g.setColor(COLOR);
    g.fillRect(0, 0, WIDTH, HEIGHT);
}
 }

错误:在这部分代码中出现“只能迭代数组或 java.lang.Iterable 的实例”错误:

public void draw(Graphics g){

    for(Ball ball : balls){

        g.setColor(new Color(red, green, blue));
        g.fillOval((int)(x - radius), (int)(y - radius), (int)(2 * radius), (int)(2 * radius));
    }
}
4

3 回答 3

2

首先,如果你想渲染多个球,你应该创建另一个类来包含绘制一个球所需的所有属性(甚至可能是一个draw (Graphics g)委托绘图的方法)。然后你会在你的BouncingBalls类上有一个球列表,应该迭代并在paintComponent方法上绘制。

也就是说,您的mouseClicked处理程序只会创建一个新Ball实例并将其添加到列表中。

编辑: 绘图过程将如何在您的DrawCanvas班级中的示例:

class DrawCanvas {
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        container.draw(g);

        for (Ball ball : balls)
            //the draw method should only care of the specific ball instance 
            //you are calling it from
            ball.draw(g);
    }
...

我认为您在将问题分成类并使它们的实例合作做您想做的事情时遇到了问题。如果您确实对此有疑问,我建议您阅读一些有关该主题的文章/书籍,以更好地了解类和对象的概念以及它们的工作原理;它肯定会帮助您轻松进行编程。

于 2013-01-28T23:58:19.157 回答
1

您需要将 MouseListener 添加到组件中:

public BouncingBalls() {
  this.addMouseListener(this); // <-- Add this object as a MouseListener.
  this.setPreferredSize(new Dimension(BOX_WIDTH, BOX_HEIGHT));
于 2013-01-28T23:54:28.900 回答
0

尝试在您的main方法中使用此代码:

frame.addMouseListener(this);

您需要将鼠标侦听器添加到框架/面板。

(由您回复评论)或者,如果您想将侦听器添加到面板,首先您必须调用

setFocusable(true);
requestFocusInWindow();

在你的BouncingBalls构造函数中。然后,您可以使用以下命令将鼠标侦听器添加到面板:

addMouseListener(this);

这是因为面板最初没有焦点。

但是,最简单的方法是将鼠标侦听器添加到框架中。

于 2013-01-28T23:55:21.823 回答