为什么我的代码“Bouncing ball”不起作用?

为什么我的代码“Bouncing ball”不起作用?,第1张

为什么我的代码“Bouncing ball”不起作用?

基本上,什么都没有移动。

每次

SwingTimer
滴答作响,您要做的就是重新粉刷。

您需要将移动逻辑移至

actionPerformed
ActionListener
注册的方法Timer

更像…

public void StartBouncingBallTest() {    timer.start();}//...class TimerListener implements ActionListener {    @Override    public void actionPerformed(ActionEvent e) {        if (x > 0 && y > 0) { x += dx; y += dy;        }        else if (x == 0) { x -= dx; y += dy;        }        else if (y + (2 * radius) > getHeight()) { x += dx; y -= dy;        }        else if (y == 0) { x += dx; y -= dy;        }        else if (x + (2 * radius) > getWidth()) { x -= dx; y += dy;        }        repaint();    }}

这样,每次Timer打勾时,您都在相应地更新球的位置…

更新了工作示例

我做了两个更改。我将设置TimerListener为的内部类Ball,从而允许它访问的变量和方法,Ball并修改了您的
运动逻辑,使其可以正常工作

class Ball extends JPanel {    private int radius = 10;    private int x;    private int y;    private int dx = 3;    private int dy = 3;    private Timer timer = new Timer(20, new TimerListener());    public void StartBouncingBallTest() {        timer.start();    }    public void StopBouncingBallTest() {        timer.stop();    }    @Override    protected void paintComponent(Graphics g) {        super.paintComponent(g);        g.setColor(Color.GREEN);        g.fillOval(x, y, 2 * radius, 2 * radius);    }    class TimerListener implements ActionListener {        @Override        public void actionPerformed(ActionEvent e) { if (x < 0 || x + (2 * radius) > getWidth()) {     dx *= -1; } if (y < 0 || y + (2 * radius) > getHeight()) {     dy *= -1; } x += dx; y += dy; repaint();        }    }}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5489389.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-12
下一篇2022-12-12

发表评论

登录后才能评论

评论列表(0条)

    保存