GUI——移动的变色小球

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Animation {
    int x=70;
    int y=70;


    public static void main(String[] args){
        Animation gui=new Animation();
        gui.go();
    }
    public void go(){
        JFrame frame=new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        MyDrawPanel drawPanel=new MyDrawPanel(); //创建出widget
        frame.getContentPane().add(drawPanel);

        frame.setSize(300,300);
        frame.setVisible(true);

        for(int i=0;i<130;i++)
        {
            x++;
            y++;
            drawPanel.repaint();
            try {
                 Thread.sleep(50);
                }catch (Exception e){ }
            }
        }
    class MyDrawPanel extends JPanel{
        public void paintComponent(Graphics g){
            g.fillRect(0,0,this.getWidth(),this.getHeight());
            //达到移动效果 使他每动一次 填充画面

            int red=(int)(Math.random()*255);
            int green=(int)(Math.random()*255);
            int blue=(int)(Math.random()*255);

            Color randomColor=new Color(red,green,blue);
            g.setColor(randomColor);
            g.fillOval(x,y,40,40);
        }
    }
}




你可能感兴趣的:(软工一,swing,java)