java模拟时钟

2020-09-13 社会 109阅读
import java.awt.*;
import java.applet.Applet;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ClockApplet extends Applet implements Runnable //Applet支持线程
{
private Thread athread; //线程
private SimpleDateFormat sdateformat; //日期格式
public void init()
{
this.setBackground(Color.white);
this.athread = null;
}
public void paint(Graphics g)
{
this.sdateformat = new SimpleDateFormat("hh时mm分ss秒");
g.drawString(this.sdateformat.format(new Date()),25,131);

Calendar rightnow = Calendar.getInstance();
int second = rightnow.get(Calendar.SECOND);
int minute = rightnow.get(Calendar.MINUTE);
int hour = rightnow.get(Calendar.HOUR);

//半径
int R_H = 20,R_M = 4,R_S = 4;
//时针的坐标
//x ====(9-3)[0-6] (3-9)[6-0]
//y ====(12-6)[0-6] (6-12)[6-0]
int H_x ;
int H_y;
//x
if(hour == 0)
{
hour = 12;
}
if( hour >= 3 && hour <= 9 )
{
H_x = R_H*Math.abs(hour - 9);
}
else
{
if(hour > 9)
{
H_x = R_H*Math.abs(hour - 9);
}
else
{
H_x = R_H*Math.abs(hour+3);
}
}
//y
if( hour >= 6 && hour <= 12 )
{
H_y = R_H*Math.abs(hour - 12);
}
else
{
H_y = R_H*hour;
}

//分针的坐标
int M_x;
int M_y;

if(minute == 0)
{
minute = 60;
}
if( minute >= 15 && minute <= 45 )
{
M_x = R_M*Math.abs(minute - 45);
}
else
{
if(minute > 45)
{
M_x = R_M*Math.abs(minute - 45);
}
else
{
M_x = R_M*Math.abs(minute+15);
}
}
//y
if( minute >= 30 && minute < 60 )
{
M_y = R_M*Math.abs(minute - 60);
}
else
{
M_y = R_M*minute;
}

//秒针的坐标
int S_x;
int S_y;

if(second == 0)
{
second = 60;
}
if( second >= 15 && second <= 45 )
{
S_x = R_S*Math.abs(second - 45);
}
else
{
if(second > 45)
{
S_x = R_S*Math.abs(second - 45);
}
else
{
S_x = R_S*Math.abs(second+15);
}
}
//y
if( second >= 30 && second <= 60 )
{
S_y = R_S*Math.abs(second - 60);
}
else
{
S_y = R_S*second;
}
// g.drawString(String.valueOf(second),25,50);
// g.drawString(String.valueOf(minute),25,60);
// g.drawString(String.valueOf(hour),25,70);
// g.drawString(String.valueOf(H_x),25,80);
// g.drawString(String.valueOf(H_y),25,90);
g.drawOval(0,0,120,120);//距离相差10像素
g.setColor(Color.darkGray);
g.drawString("9",5,65);
g.drawString("3",110,65);
g.drawString("12",55,15);
g.drawString("6",55,115);

g.drawString("1",80,20);
g.drawString("2",100,40);
g.drawString("4",100,90);
g.drawString("5",80,110);

g.drawString("7",30,110);
g.drawString("8",10,90);
g.drawString("10",10,40);
g.drawString("11",30,20);

g.setColor(Color.red);
g.drawLine(60,60,H_x,H_y);//前一个点表示起点,另一个表示终点
g.setColor(Color.blue);
g.drawLine(60,60,M_x,M_y);
g.setColor(Color.yellow);
g.drawLine(60,60,S_x,S_y);
}
public void start()
{
if(athread == null)
{
athread = new Thread(this);
athread.start();
}
}
public void stop()
{
if(athread != null)
{
athread.interrupt();
athread = null;
}
}
public void run()
{
while(athread != null)
{
repaint();
try
{
athread.sleep(1000);
}
catch(InterruptedException e)
{
}
}
}
}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com