public class AnimatePlate extends JFrame{
private static final int DELAY=100;
private int offset;
//窗口的边框
Insets inset;
//颜色数组
Color colors[]={Color.RED,Color.ORANGE,Color.YELLOW,Color.GREEN,Color.BLUE,Color.MAGENTA,Color.CYAN};
//画屏函数
public void paint(Graphics g){
super.paint(g);
if(inset==null){
inset=this.getInsets();
}
int x=inset.left;
int y=inset.top;
int width=this.getWidth()-x-inset.right;
int height=this.getHeight()-y-inset.bottom;
int start=0;
int steps=colors.length;
int stepSize=360/steps;
//如果不能整除,画一周后将会留下一部分区域。
int lack=360%steps;
synchronized (colors) {
for(int i=0;i<steps;i++){
if(lack!=0){
//画最后一块区域,加上少画的角度
if(i==steps-1){
stepSize+=lack;
}
}
int k=(i+offset)%colors.length;
g.setColor(colors[k]);
//画椭圆,前四个参数指定外接矩形,然后起始角度,要填充角度
g.fillArc(x, y, width, height,start, stepSize);
start+=stepSize;
}
}
}
public void start(){
TimerTask task=new TimerTask(){
@Override
public void run() {
offset++;
if(offset>=colors.length){
offset=0;
}
repaint();
}
};
Timer timer=new Timer();
timer.schedule(task, 0, AnimatePlate.DELAY);
}
public static void main(String[] args) {
AnimatePlate frame=new AnimatePlate();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
frame.start();
}
}