本帖最后由 陈少文 于 2012-7-20 12:17 编辑
//画秒针
/*
思路:
1 >定义一个ClockPanel类继承JPanel,并覆盖paintComponent()方法
2> 创建定时器Timer对象
3>画秒针,分针,时针
*/
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.Timer;
class ClockPanel extends JPanel implements ActionListener
{
private int hour; //时
private int minute; //分
private int second; //秒
ClockPanel() //构造方法
{
Timer timer = new Timer(1000,this); //每隔1秒产生一次ActionEvent事件
timer.start(); //启动该Timer
}
protected void paintComponent(Graphics g) //重写paintComponent(Graphics g)方法
{
super.paintComponent(g); //确保绘图区域干净
setCurrentTime(); //重新设置时间
int clockRadius = 120; //定义表盘半径
int xCenter = 150; //定义表盘圆心坐标
int yCenter = 125;
//画时间刻度盘
//外接矩形,xCenter-clockRadius, yCenter- clockRadius左上角,2*clockRadius, 2*clockRadius长和宽
g.drawOval(xCenter-clockRadius, yCenter- clockRadius, 2*clockRadius, 2*clockRadius);
//为了画出的图形不出现重叠,就+-值,进行错位
g.drawString("12", xCenter-5, yCenter-clockRadius+12);
g.drawString("9", xCenter-clockRadius+3, yCenter+5);
g.drawString("3", xCenter+clockRadius-10, yCenter+3);
g.drawString("6", xCenter-5, yCenter+clockRadius-3);
//画秒针
int sLength = (int)(clockRadius*0.8); //秒针长度
//定义秒针端点(xSecond,ySecond)
int xSecond = (int)(xCenter+sLength*Math.sin(second*(2*Math.PI/60)));
int ySecond = (int)(yCenter-sLength*Math.cos(second*(2*Math.PI/60)));
g.setColor(Color.RED);
g.drawLine(xCenter,yCenter,xSecond,ySecond);
//画分针
int mLength = (int)(clockRadius*0.6);
int xMinute = (int)(xCenter+mLength*Math.sin(minute*(2*Math.PI/60)));
int yMinute = (int)(yCenter-sLength*Math.cos(minute*(2*Math.PI/60)));
g.setColor(Color.BLUE);
g.drawLine(xCenter, yCenter, xMinute, yMinute);
//画时针
int hLength = (int)(clockRadius*0.4);
int xHour = (int)(xCenter+hLength*Math.sin((hour%12+minute/60.0)*(2*Math.PI/12)));
int yHour = (int)(yCenter-sLength*Math.cos((hour%12+minute/60.0)*(2*Math.PI/12)));
g.setColor(Color.BLACK);
g.drawLine(xCenter, yCenter, xHour, yHour);
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
g.drawString("当前时间:"+sdf.format(d),100,265);
}
public void actionPerformed(ActionEvent e)
{
//重绘此组件
repaint();
}
//获取系统当前时间,给hour,minute,second赋值
public void setCurrentTime()
{
Calendar cal = new GregorianCalendar();
this.hour = cal.get(Calendar.HOUR_OF_DAY);
this.minute = cal.get(Calendar.MINUTE);
this.second = cal.get(Calendar.SECOND);
}
}
public class ClockDemo extends JApplet
{
public void init()
{
ClockPanel cp = new ClockPanel();
add(cp);
}
}
|