【问题标题】:Multiple bouncing balls triggered by MouseListener由 MouseListener 触发的多个弹跳球
【发布时间】:2013-01-30 04:33:38
【问题描述】:

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

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

BouncingBalls 类

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

【问题讨论】:

  • 我试过了,但没有奏效。 addMouseListener(this);应该工作正常吗?但事实并非如此。
  • 你要把MouseListener 添加到什么地方?
  • 对于移动问题:尝试在 move 方法中添加 print 语句以查看其末尾的 x 和 y 的实际值,或者如果您现在如何使用调试器,请在该方法并查看它是否按预期工作。关于鼠标侦听器:您似乎没有像其他人建议的那样将鼠标侦听器添加到您的 BouncingBalls 实例中。即使它不起作用,也将其发布在代码上,以便我们看到整个事情。
  • 哦,你忘记开始你的话题了。这可能是运动问题的问题。
  • 是的,我想通了,抱歉更新晚了。我现在唯一的问题是我无法创建多个球。当我点击屏幕时,同一个球只是保持速度而不是创造一个新球。我会在一分钟内更新我的代码。

标签: java awt mouselistener


【解决方案1】:

首先,如果您想渲染多个球,您应该创建另一个类来包含绘制球所需的所有属性(甚至可以使用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
  • @Doorknob 我假设他遇到了逻辑问题,而您假设他遇到了技术问题。在我看来,我的回答和你的一样有效:)
  • 其实这是有道理的。 :P 删除 -1
  • 我必须列一个清单吗?我创建了一个名为 Ball(extends BouncingBalls) 的类并在其中创建了一个绘图方法,但我无法调用该方法。
  • @Miral Ball 类不应该扩展BouncingBalls,它应该是另一个可以帮助您保持每个球个性化的类。我提到的列表将包含您应用程序中的所有球,您的paintComponent 方法应该迭代并绘制所有这些球。您可以将要绘制的逻辑放入paintComponent 方法中,也可以将其抽象到Ball 上的draw 方法中。无论如何,你应该用你尝试过的东西更新你的主要帖子,这样我们就可以更好地了解你的尝试,以便我们可以帮助你!
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    frame.addMouseListener(this);
    

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

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

    setFocusable(true);
    requestFocusInWindow();
    

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

    addMouseListener(this);
    

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

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

    【讨论】:

    • 一个组件不需要可聚焦来接收鼠标事件,只需要按键事件;) - 事实上,鼠标点击将使窗口激活并且组件(如果它有能力)聚焦无论如何....另外,鼠标监听器应该被添加到BouncingBalls面板而不是框架中,因为如果你将它添加到框架中,它可能会被其他组件消耗,你需要对鼠标点击做出反应在面板而不是框架的上下文中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 2020-02-22
    • 2013-05-23
    • 2013-05-14
    • 2012-10-12
    • 1970-01-01
    相关资源
    最近更新 更多