Java实现动态模拟时钟
本文实例为大家分享了java动态模拟时钟的具体代码,供大家参考,具体内容如下
应用名称:java动态模拟时钟
用到的知识:javaGUI,java绘图
开发环境:win10+eclipse+jdk1.8
功能说明:通过java绘图画出一个虚拟的动态时钟
效果图:
源代码:
importjavax.swing.*;
importjava.awt.*;
importjava.util.*;
importjava.lang.Thread;
importjava.text.DecimalFormat;
publicclassStillClockextendsJPanel{
/**
*@paramargs
*/
privateinthour;
privateintminute;
privateintsecond;
//构造函数
publicStillClock(){
setCurrentTime();
}
//返回小时
publicintgetHour(){
returnhour;
}
publicintgetMinute(){
returnminute;
}
publicintgetSecond(){
returnsecond;
}
//绘制时钟
protectedvoidpaintComponent(Graphicsg){
super.paintComponent(g);
//初始化
intclockRadius=(int)(Math.min(getWidth(),getHeight())*0.8*0.5);
intxCenter=getWidth()/2;
intyCenter=getHeight()/2;
//画圆
g.setColor(Color.black);
g.drawOval(xCenter-clockRadius,yCenter-clockRadius,2*clockRadius,2*clockRadius);
g.drawString("12",xCenter-5,yCenter-clockRadius+15);
g.drawString("9",xCenter-clockRadius+3,yCenter+5);
g.drawString("3",xCenter+clockRadius-10,yCenter+3);
g.drawString("6",xCenter-3,yCenter+clockRadius-3);
//画秒针
intsLength=(int)(clockRadius*0.8);
intxSecond=(int)(xCenter+sLength*Math.sin(second*(2*Math.PI/60)));
intySecond=(int)(yCenter-sLength*Math.cos(second*(2*Math.PI/60)));
g.setColor(Color.red);
g.drawLine(xCenter,yCenter,xSecond,ySecond);
//画分针
intmLenth=(int)(clockRadius*0.65);
intxMinute=(int)(xCenter+mLenth*Math.sin(minute*(2*Math.PI/60)));
intyMinute=(int)(xCenter-mLenth*Math.cos(minute*(2*Math.PI/60)));
g.setColor(Color.blue);
g.drawLine(xCenter,yCenter,xMinute,yMinute);
//画时针
inthLength=(int)(clockRadius*0.5);
intxHour=(int)(xCenter+hLength*Math.sin((hour%12+minute/60.0)*(2*Math.PI/12)));
intyHour=(int)(yCenter-hLength*Math.cos((hour%12+minute/60.0)*(2*Math.PI/12)));
g.setColor(Color.green);
g.drawLine(xCenter,yCenter,xHour,yHour);
//画数字时钟
g.setColor(Color.black);
DecimalFormats=newDecimalFormat("00");
g.drawString(s.format(getHour())+":"+s.format(getMinute())+":"+s.format(getSecond()),xCenter-22,yCenter-clockRadius-15);
}
publicvoidsetCurrentTime(){
Calendarcalendar=newGregorianCalendar();
this.hour=calendar.get(Calendar.HOUR_OF_DAY);
this.minute=calendar.get(Calendar.MINUTE);
this.second=calendar.get(Calendar.SECOND);
}
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
JFrameframe=newJFrame("DiaplayClock");
frame.setResizable(false);
frame.setTitle("DiaplayClock");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,350);
frame.setVisible(true);
while(true){
StillClockclock=newStillClock();
frame.getContentPane().add(clock);
clock.setVisible(true);
frame.validate();
try{
Thread.sleep(1000);
}
catch(InterruptedExceptione){
e.printStackTrace();
}
clock.setVisible(false);
frame.remove(clock);
clock=null;
frame.validate();
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。