MouseListener触发多个弹跳球

时间:2013-01-28 23:50:29

标签: java awt mouselistener

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

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

BouncingBalls Class

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);
}
 }

错误:我得到&#34;只能遍历数组或java.lang.Iterable&#34;的实例。这段代码中的错误:

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));
    }
}

3 个答案:

答案 0 :(得分: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);
    }
...

我认为您在将问题分成类并使其实例合作以执行您想要的操作时遇到问题。如果您确实对此有疑问,我建议您阅读一些关于该主题的文章/书籍,以更好地了解类和对象的概念以及它们如何工作;它绝对可以帮助您轻松完成编程。

答案 1 :(得分:1)

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

public BouncingBalls() {
  this.addMouseListener(this); // <-- Add this object as a MouseListener.
  this.setPreferredSize(new Dimension(BOX_WIDTH, BOX_HEIGHT));

答案 2 :(得分:0)

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

frame.addMouseListener(this);

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

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

setFocusable(true);
requestFocusInWindow();

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

addMouseListener(this);

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

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