repaint重绘不消除之前图像问题

来源:互联网 发布:怎么看淘宝关注的直播 编辑:程序博客网 时间:2024/04/29 14:09

好久没写过Java界面的程序,一写就搞不定:
如下,就是一个小球在在几面里来回移动的问题

public class ReboundPanel extends JPanel {    private final int WIDTH = 300, HEIGHT = 100;    private final int DELAY = 20;    private Timer timer;    private int x,y ,moveX,moveY;    public ReboundPanel() {        timer  = new Timer(DELAY,new ActionListener() {            @Override            public void actionPerformed(ActionEvent e) {                x += moveX;                y += moveY;                if(x<=0 ||x >= WIDTH - 30) {                    moveX = moveX * -1;                }                if(y<=0 ||y >= HEIGHT - 30) {                    moveY = moveY * -1;                }                repaint();            }        });        x = 0;        y = 40;        moveX = moveY = 3;        setPreferredSize(new Dimension(WIDTH, HEIGHT));        setBackground(Color.black);        timer.start();    }    @Override    public void paint(Graphics g) {        Color c = g.getColor();        g.setColor(Color.RED);        g.fillOval(x, y, 30, 30);        g.setColor(c);    }}

结果却是这样:
这里写图片描述
对,之前的图像没有消除,查了资料,在继承了JPanel类后使用paint()方法应该调用一下父类的paint()方法,继承JFrame类的类使用paint()方法测试不调用父类方法并不会出现这样的情况:

    public void paint(Graphics g) {        super.paint(g);//调用父类方法        Color c = g.getColor();        g.setColor(Color.RED);        g.fillOval(x, y, 30, 30);        g.setColor(c);    }

结果:
这里写图片描述

0 0
原创粉丝点击