栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

为什么我的代码“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();        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/497267.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号