注册 登录
编程论坛 JAVA论坛

关于repaint方法

不落夕阳 发布于 2018-07-12 17:41, 1807 次点击
import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;


public class TestRepaint extends JFrame implements Runnable{
    int x,y;
    Graphics g;
    public TestRepaint(){
        this.setTitle("画图");
        this.setSize(1000,1000);
        this.setVisible(true);
        
        JPanel  panel = new JPanel();
        
        this.add(panel);
    }
    @Override
    public void paint(Graphics g){
        g.setColor(Color.RED);
        g.fillOval((int)(Math.random()*1000), (int)(Math.random()*1000),20, 20);
    }
    public static void main(String[] args) {
        TestRepaint tr = new TestRepaint();
        new Thread(tr).start();
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        
        while(true){
            repaint();
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}如何做到:当生成一个实心圆的时候上一个院被清除。也就是说画布上只有一个随机圆在跳动
1 回复
#2
林月儿2018-07-14 15:56
程序代码:
public class Test extends JFrame implements Runnable{
    /**
     *
     
*/
    private static final long serialVersionUID = 1L;
    int x,y;
    Graphics g;
    public Test(){
        setTitle("画图");
        setSize(1000,1000);
        setVisible(true);
        setDefaultCloseOperation(3);
    }
    @Override
    public void paint(Graphics g){
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 1000, 1000);
        g.setColor(Color.RED);
        g.fillOval((int)(Math.random()*1000), (int)(Math.random()*1000),20, 20);
    }
    public static void main(String[] args) {
        Test tr = new Test();
        new Thread(tr).start();
    }
    @Override
    public void run() {
        
        while(true){
            repaint();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
1