代码改变世界

Sky

2017-12-13 18:41  沈橙Anei  阅读(290)  评论(0编辑  收藏  举报

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Sky extends JLabel implements ActionListener { //标签类JLabel的子类--刻画天空
Earth earth;
Timer timer; //计时器
double pointX[]=new double[360], //double型数组pointX刻画水平坐标-地球相对于天空的
pointY[]=new double[360]; //double型数组pointY刻画垂直坐标-地球相对于天空的
int w=400,h=400,i=0;
Sky() {
timer=new Timer(100,this); //创建timer--振铃间隔是100毫秒--当前Sky对象为其监视器
earth = new Earth(); //构造了一个地球(实际上是一个标签对象)
earth.setSize(200,200); //地球(标签对象)大小为200*200
add(earth); //地球位于刻画天空的标签里(标签也可以是容器)
pointX[0]=0; //地球运动轨道的半径h/2
pointY[0]=h/2;
double angle=1*Math.PI/180; //刻度为1度-弧度
for(int i=0;i<359;i++) { //计算出数组中各个元素的值--圆上的坐标点
pointX[i+1]=pointX[i]*Math.cos(angle)-pointY[i]*Math.sin(angle); //以圆中心为(0,0),第一个点为(0,h/2),顺时
pointY[i+1]=pointY[i]*Math.cos(angle)+pointX[i]*Math.sin(angle); //针旋转1弧度后的坐标
}
for(int i=0;i<360;i++) {
pointX[i]=0.5*pointX[i]+w/2; //坐标缩放平移--将圆中心变为(w/2,h/2)
pointY[i]=0.5*pointY[i]+h/2; //轨道圆大小缩小1倍
}
timer.start(); //计时器启动--每隔100毫秒就会触发ActionEvent
}
public void actionPerformed(ActionEvent e) {
i=(i+1)%360; //0~359循环变化
earth.setLocation((int)pointX[i]-100,(int)pointY[i]-100); //设置earth对象(标签)在sky对象(标签)上的位置
}
}