电子时钟java写的
java 模拟时钟问题
java 模拟时钟问题编写的JA V A动态模拟时钟,结果每次都走三个格(就相当于1s走了3s的时间)import java.applet.Applet;import java.awt.Color;import java.awt.Graphics;import java.text.SimpleDateFormat;import java.util.Calendar;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;//xif(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);}}//yif( 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);}}//yif( 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);}}//yif( 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){}}}}。
用JAVA实现一个时钟
⽤JAVA实现⼀个时钟⽤JAVA实现⼀个时钟⽤图形库绘制表盘,然后⽤事件处理机制刷新窗⼝,反复重绘,让表针转动起来import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.awt.geom.*;import java.awt.geom.Line2D.Double;import java.math.*;import java.time.LocalTime;public class MyClock {public static void main(String[] args) {// TODO Auto-generated method stubActionListener listener = new TimerClock();Timer t = new Timer(1000, listener);t.start();//System.exit(0);}}class ClockWindow extends JFrame {ClockWindow() {add(new ClockInfo());pack();}}class ClockInfo extends JComponent {private static final int DEFAULT_WIDTH = 500;private static final int DEFAULT_HEIGHT = 500;public void paintComponent(Graphics g) {Graphics2D g2 = (Graphics2D) g;g2.draw(new Ellipse2D.Double(50.0, 50.0, 400.0, 400.0));//圆⼼为250, 250//绘制⼩时刻度g2.setPaint(Color.red);double r1 = 190, r2 = 200;double cx = 250.0, cy = 250.0;for(double i = 0; i < 2.0 * Math.PI; i += (Math.PI / 6.0)) {double lx, ly, rx, ry;lx = r1 * Math.sin(i);ly = r1 * Math.cos(i);rx = r2 * Math.sin(i);ry = r2 * Math.cos(i);g2.draw(new Line2D.Double(cx + lx, cy - ly, cx + rx, cy - ry));}//绘制分钟刻度r1 = 195.0;for(double i = 0; i < 2.0 * Math.PI; i += (Math.PI / 30.0)) {double lx, ly, rx, ry;lx = r1 * Math.sin(i);ly = r1 * Math.cos(i);rx = r2 * Math.sin(i);ry = r2 * Math.cos(i);g2.draw(new Line2D.Double(cx + lx, cy - ly, cx + rx, cy - ry));}//绘制指针double hour = LocalTime.now().getHour() * Math.PI / 6.0;double minute = LocalTime.now().getMinute() * Math.PI / 30.0;double second = LocalTime.now().getSecond() * Math.PI / 30.0;//时针g2.setPaint(Color.black);g2.setStroke(new BasicStroke(4.0f));g2.draw(new Line2D.Double(cx, cy, cx + 120.0 * Math.sin(hour), cy - 120.0 * Math.cos(hour)));//分针g2.setPaint(Color.green);g2.setStroke(new BasicStroke(2.0f));g2.draw(new Line2D.Double(cx, cy, cx + 140.0 * Math.sin(minute), cy - 140.0 * Math.cos(minute)));//秒针g2.setPaint(Color.red);g2.setStroke(new BasicStroke(1.0f));g2.draw(new Line2D.Double(cx, cy, cx + 160.0 * Math.sin(second), cy - 160.0 * Math.cos(second)));//⽂字Font f = new Font("Serif", Font.PLAIN, 30);//逻辑字体g2.setFont(f);g2.setColor(Color.orange);int h = LocalTime.now().getHour();int m = LocalTime.now().getMinute();int s = LocalTime.now().getSecond();g2.drawString("" + h + ":" + m + ":" + s,10,50);}public Dimension getPreferredSize() {return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }}class TimerClock implements ActionListener {ClockWindow frame;TimerClock() {frame = new ClockWindow();frame.setTitle("MyClock");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);}@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubframe.repaint();}}。
java实验一:写一个桌面时钟
java实验⼀:写⼀个桌⾯时钟⼀共有三个类:这个是第⼀个,主函数类:public class Programe extends JFrame {/** 四个部分: 1.画出窗体和⾯板 2.画出指针 3.时间转换的算法 4.让指针动起来*/public static void main(String[] string) {Programe frame = new Programe();// 创建窗体对象frame.setVisible(true);// 设置窗体可见,没有该语句,窗体将不可见,此语句必须有,否则没有界⾯就没有意义}public Programe() {setUndecorated(false);// 打开窗体修饰setAlwaysOnTop(true);// 窗体置顶getContentPane().setLayout(new BorderLayout()); // 在窗体的基础上加⼊⾯板:Panel ⽽后就可以在⾯板上进⾏其他操作 // 指定的组件之间的⽔平间距构造⼀个边界布局setBounds(100, 30, 217, 257);// ⽤于设置窗⼝尺⼨和位置;ClockPaint clockPaint = new ClockPaint();// 创建时钟⾯板getContentPane().add(clockPaint);new Thread() {// 继承Thread类创建线程,更新时钟⾯板界⾯@Overridepublic void run() {// 重写run⽅法try {while (true) {sleep(1000);// 休眠1秒clockPaint.repaint();// 重新绘制时钟⾯板界⾯}} catch (InterruptedException e) {e.printStackTrace();// 在命令⾏打印异常信息在程序中出错的位置及原因。
}}}.start();}}这个是第⼆个,画时钟的类:package clock;import java.awt.BasicStroke;import java.awt.Color;import java.awt.Dimension;import java.awt.Graphics;import java.awt.Graphics2D;import javax.swing.ImageIcon;import javax.swing.JPanel;public class ClockPaint extends JPanel {private static final BasicStroke H = new BasicStroke(4);// 指针粗细private static final BasicStroke M = new BasicStroke(3);private static final BasicStroke S = new BasicStroke(2);private final static int secLen = 60; // 指针长度private final static int minuesLen = 55;private final static int hoursLen = 36;ImageIcon background;// 背景private int X;// 中⼼坐标private int Y;public ClockPaint() {background = new ImageIcon(getClass().getResource("时钟.jpg"));// 加载图⽚int Width = background.getIconWidth();// 获取图⽚宽度X = Width / 2 + 2;// 获取图⽚中间坐标int Height = background.getIconHeight();// 获取图⽚长度Y = Height / 2 - 8;// 获取图⽚中间坐标setPreferredSize(new Dimension(Width, Height));// 设置最好的⼤⼩(固定⽤法)}public void paint(Graphics g) {Graphics2D g2 = (Graphics2D) g;g2.drawImage(background.getImage(), 0, 0, this);ClockData data = new ClockData(secLen, minuesLen, hoursLen);// 绘制时针g2.setStroke(H);// 设置时针的宽度g2.setColor(Color.RED);// 设置时针的颜⾊g2.drawLine(X, Y, X + data.hX, Y - data.hY);// 绘制时针// 绘制分针g2.setStroke(M);// 设置分针的宽度g2.setColor(Color.orange);// 设置时针的颜⾊g2.drawLine(X, Y, X + data.mX, Y - data.mY);// 绘制分针// 绘制秒针g2.setStroke(S);// 设置秒针的宽度g2.setColor(Color.GREEN);// 设置时针的颜⾊g2.drawLine(X, Y, X + data.sX, Y - data.sY);// 绘制秒针// 绘制中⼼圆g2.setColor(Color.BLUE);g2.fillOval(X - 5, Y - 5, 10, 10);}}这个是第三个,获取时钟的数据:package clock;import static java.util.Calendar.HOUR;import static java.util.Calendar.MINUTE;import static java.util.Calendar.SECOND;import java.util.Calendar;public class ClockData {public int sX, sY, mX, mY, hX, hY;public ClockData(int secLen, int minuesLen, int hoursLen) {Calendar calendar = Calendar.getInstance();// 获取⽇历对象int sec = calendar.get(SECOND);// 获取秒值int minutes = calendar.get(MINUTE);// 获取分值int hours = calendar.get(HOUR);// 获取时值// 计算⾓度int hAngle = hours * 360 / 12 + (minutes / 2) ;// 时针⾓度(每分钟时针偏移⾓度)int sAngle = sec * 6; // 秒针⾓度int mAngle = minutes * 6 + (sec / 10);// 分针⾓度// 计算秒针、分针、时针指向的坐标sX = (int) (secLen * Math.sin(Math.toRadians(sAngle)));// 秒针指向点的X坐标(将⾓度转换为弧度) sY = (int) (secLen * Math.cos(Math.toRadians(sAngle))); // 秒针指向点的Y坐标mX = (int) (minuesLen * Math.sin(Math.toRadians(mAngle))); // 分针指向点的X坐标mY = (int) (minuesLen * Math.cos(Math.toRadians(mAngle))); // 分针指向点的Y坐标hX = (int) (hoursLen * Math.sin(Math.toRadians(hAngle))); // 时针指向点的X坐标hY = (int) (hoursLen * Math.cos(Math.toRadians(hAngle))); // 时针指向点的Y坐标}}以上参考了其他⼤佬的代码,等我找到原地址再补上:D做了部分修改,加了部分注释,java⼩⽩还请客官您多多包含呀!。
java简易电子时钟代码
import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;import java.text.SimpleDateFormat;public class ClockJFrame extends JFrame{private Date now=new Date();Panel buttons=new Panel();Button button_start=new Button("启动");Button button_interrupt=new Button("停止");Clock label=new Clock();public ClockJFrame() //构造方法{super("电子时钟");this.setBounds(300,240,300,120);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.setLayout(new BorderLayout());this.getContentPane().add("North",label);//初始化一个容器,用来在容器上添加一个标签this.getContentPane().add("South",buttons);buttons.setLayout(new FlowLayout());buttons.add(button_start);buttons.add(button_interrupt);setVisible(true);}private class Clock extends Label implements ActionListener,Runnable{ private Thread clocker=null;private Date now=new Date();public Clock(){button_start.addActionListener(this);button_interrupt.addActionListener(this);SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");//可以方便地修改日期格式String t = dateFormat.format( now );this.setText(t);}public void start(){if(clocker==null){clocker=new Thread(this);clocker.start();}}public void stop(){clocker=null;}public void run(){Thread currentThread=Thread.currentThread();while(clocker==currentThread){now=new Date();SimpleDateFormat dateFormat = newSimpleDateFormat("HH:mm:ss");//可以方便地修改日期格式String t = dateFormat.format( now );this.setText(t);try{clocker.sleep(1000);}catch(InterruptedException ie){JOptionPane.showMessageDialog(this,"Thread error:+ie");}}}public void actionPerformed(ActionEvent e){if (e.getSource()==button_start) {clocker = new Thread(this); //重新创建一个线程对象clocker.start();button_start.setEnabled(false);button_interrupt.setEnabled(true);}if (e.getSource()==button_interrupt) //单击中断按钮时{clocker.stop(); //设置当前线程对象停止标记button_start.setEnabled(true);button_interrupt.setEnabled(false);}}}//内部类结束public static void main(String[] args) {ClockJFrame time=new ClockJFrame();}}运行结果:。
Java模拟时钟制作案例
程序代码
主类
程序代码
程序代码
运行效果
运行效果
面板刻度
绘制刻度
l1=new Line2D.Double[60]; for(int i=0 ;i<l1.length;i++) { double b[]=new double[4]; int j; if(i%5==0){ if(i%15==0){ j=50; }else { j=60; }
构建框架
主类time1. 实现接口。 继承Jframe。 添加main方法
完善代码
添加timer 通过Date获取当前时间 通过SimpleDateFormat处理时间格式。 实例化主类,使其在控制台打印当前时间, 每隔一秒打印一次。 修改后的代码如下。
程序代码
导入类和文件。
程序代码
数字时钟
添加JLabel,在JLabel上显示时间 把JLabel添加到JFrame上。
程序代码
导入类和文件。
程序代码
数字时钟
运行效果。
绘制秒针
使用直线绘制秒针。
定义秒针Line2D.Double l Line2D.Double l =new Line2D.Double(125,50,125,125);
面板刻度
绘制刻度
}else { j=70; } b[0]=125+80*Math.cos((i*6-90)*Math.PI/180d); b[1]=125+80*Math.sin((i*6-90)*Math.PI/180f); b[2]=125+j*Math.cos((i*6-90)*Math.PI/180f); b[3]=125+j*Math.sin((i*6-90)*Math.PI/180f); l1[i] =new Line2D.Double(b[0],b[1],b[2],b[3]); }
java钟表程序
一个java的钟表程序import java.awt.*;import java.util.*;import javax.swing.*;import java.awt.event.*;public class Clock extends JPanel{int CLOCK_RADIUS=200;int X_CENTER=300,Y_CENTER=300;static int second,minute,hour;static int year,month,day,week;int xSecond,ySecond;int xMinute,yMinute;int xHour,yHour;String timeStr,str1,str2,str3;static String dateStr;javax.swing.Timer timer;static String weekDisp[]={"一","二","三","四","五","六","日"};public Clock(){setBackground(Color.white);setSize(800,800);ActionListener clockTik=new ActionListener(){public void actionPerformed(ActionEvent ec){second++;if(second==60){second=0;minute++;}if(minute==60){minute=0;hour++;}if(hour==13) hour=1;repaint();}};new javax.swing.Timer(1000,clockTik).start();}public void paint(Graphics g){int xPos,yPos;double alfa;super.paint(g);for(int i=0,num=12;i<360;i+=6){alfa=Math.toRadians(i);xPos=X_CENTER+(int)(CLOCK_RADIUS*Math.sin(alfa));yPos=Y_CENTER-(int)(CLOCK_RADIUS*Math.cos(alfa));if(i%30==0){if (num%3==0)g.setColor(Color.red);elseg.setColor(Color.black);g.drawString(""+num,xPos-5,yPos+3);num=(num+1)%12;}else{g.setColor(Color.black);g.drawString(".",xPos,yPos);}}g.fillOval(X_CENTER-4,Y_CENTER-4,8,8); //表盘中心//画秒针xSecond=(int)(X_CENTER+(CLOCK_RADIUS-10)*Math.sin(second*(2*Math.PI/60)));ySecond=(int)(Y_CENTER-(CLOCK_RADIUS-10)*Math.cos(second*(2*Math.PI/60)));g.setColor(Color.red);g.drawLine(X_CENTER,Y_CENTER,xSecond,ySecond);//画分针xMinute=(int)(X_CENTER+(CLOCK_RADIUS-40)*Math.sin((minute+second/60)*(2*3.14/60)));yMinute=(int)(Y_CENTER-(CLOCK_RADIUS-40)*Math.cos((minute+second/60)*(2*3.14/60)));g.setColor(Color.red);g.drawLine(X_CENTER,Y_CENTER,xMinute,yMinute);//画时针xHour=(int)(X_CENTER+(CLOCK_RADIUS-70)*Math.sin((hour+minute/60+second/(60*60))*(2*3.14/12))); yHour=(int)(Y_CENTER-(CLOCK_RADIUS-70)*Math.cos((hour+minute/60+second/(60*60))*(2*3.14/12)));g.setColor(Color.red);g.drawLine(X_CENTER,Y_CENTER,xHour,yHour);//显示文字式样的时间if(hour<10)str1="0"+hour+":";elsestr1=hour+":";if(minute<10)str2="0"+minute+":";elsestr2=minute+":";if(second<10)str3="0"+second;elsestr3=second+"";timeStr=str1+str2+str3;g.setFont(new Font("隶书",Font.ITALIC,20));g.drawString(timeStr,X_CENTER-40,Y_CENTER+CLOCK_RADIUS+50);g.drawString(dateStr,X_CENTER-90,Y_CENTER-CLOCK_RADIUS-50);}public void paintComponent(Graphics g)// 该方法自动调用,每次重画背景时删去原来的表盘{super.paintComponent(g);}public static void main(String args[]){JFrame clockFrame=new JFrame("钟表--clock");Container contentPane=clockFrame.getContentPane();clockFrame.setSize(800,800);//获取系统时间Calendar calendar = new GregorianCalendar();/*Date date = new Date();calendar.setTime(date);*/second=calendar.get(Calendar.SECOND);minute=calendar.get(Calendar.MINUTE);hour=calendar.get(Calendar.HOUR);if(hour>12) hour=hour-12;year=calendar.get(Calendar.YEAR);month=calendar.get(Calendar.MONTH)+1;day=calendar.get(Calendar.DAY_OF_MONTH);week=calendar.get(Calendar.DAY_OF_WEEK);dateStr=year+"年"+month+"月"+day+"日"+"星期"+weekDisp[week-1];Clock clock=new Clock();contentPane.add(clock,BorderLayout.CENTER);clockFrame.pack();clockFrame.setVisible(true);}}。
java时钟程序(图片文本框)
java时钟程序(图片文本框)import java.awt.*;import javax.swing.*;import java.util.*;//定义测试类//所有变量名冲突的变量名串1了,不过就效果不好~~ public class TimerT est{//定义主函数public static void main(String[] args){//定义JFrame类的一个对象,并创建该对象MyTimer1 f = new MyTimer1();//调用MyTimer的show()方法f.show();//---------------------------------------------------- //调用类的构造函数MyTimer myTimer=new MyTimer();//调用类的显示时间函数myTimer.displayCurrentTime();//调用类的设置时间函数myTimer.setCurrentTime();//调用类的显示时间函数myTimer.displayCurrentTime();//调用类的显示时间函数myTimer.displayCurrentTime();System.exit(0);}}//定义MyTimer类class MyTimer1 extends JFrame{ static int count=0; //判断是否重定义了时间//构造函数public MyTimer1(){//定义窗口大小setSize(320, 200);//定义窗口标题setTitle("测试自定义时钟类!");Container c = getContentPane();// new ClockCanvas("北京时间", "GMT+8")c.add(new ClockCanvas("北京时间", "GMT+8")); } }//定义接口interface TimerListener1{void timeElapsed(Timer1 t);}class Timer1 extends Thread //类Timer1{private TimerListener1 target;private int interval;public Timer1(int i, TimerListener1 t){target = t;interval = i;setDaemon(true);}public void run(){ try{while (!interrupted()){sleep(interval);target.timeElapsed(this);}}catch(InterruptedException e) {}}}class ClockCanvas extends JPanel //clockcanvas implements TimerListener1{static int seconds = 0;private String city;private GregorianCalendar calendar;//构造函数public ClockCanvas(String c, String tz){city = c;calendar = new GregorianCalendar(TimeZone.getTimeZone(tz)); Timer1 t = new Timer1(1000, this);t.start();setSize(180, 180);}//绘制钟面public void paintComponent(Graphics g){super.paintComponent(g);g.drawOval(100, 5, 120, 120);g.drawOval(101, 6, 118, 118);//分离时间double hourAngle = 2 * Math.PI* (seconds - 3 * 60 * 60) / (12 * 60 * 60);double minuteAngle = 2 * Math.PI* (seconds - 15 * 60) / (60 * 60);double secondAngle = 2 * Math.PI* (seconds - 15) / 60;g.drawLine(160, 64, 160 + (int)(20* Math.cos(hourAngle)),64 + (int)(30 * Math.sin(hourAngle)));g.drawLine(160, 65, 160 + (int)(20* Math.cos(hourAngle)),65 + (int)(30 * Math.sin(hourAngle)));g.drawLine(160, 66, 160 + (int)(20* Math.cos(hourAngle)),66 + (int)(30 * Math.sin(hourAngle)));g.drawLine(160, 63, 160 + (int)(20* Math.cos(hourAngle)),63 + (int)(30 * Math.sin(hourAngle)));g.drawLine(160, 67, 160 + (int)(20* Math.cos(hourAngle)),67 + (int)(30 * Math.sin(hourAngle)));g.drawLine(160, 65, 160 + (int)(32* Math.cos(minuteAngle)),65 + (int)(40 * Math.sin(minuteAngle)));g.drawLine(160, 64, 160 + (int)(32* Math.cos(minuteAngle)),64 + (int)(40 * Math.sin(minuteAngle)));g.drawLine(160, 65, 160 + (int)(55* Math.cos(secondAngle)),65 + (int)(45 * Math.sin(secondAngle)));g.drawString(city, 130, 150);//*/}public void timeElapsed(Timer1 t){calendar.setTime(new Date());if(MyTimer1.count==1) {int a=1;seconds=MyTimer.intHour*60*60+MyTimer.intMinute*60+ MyTimer.intSecond; seconds+=a;//a为秒自加repaint();}else{ seconds = calendar.get(Calendar.HOUR) * 60 * 60+ calendar.get(Calendar.MINUTE) * 60+ calendar.get(Calendar.SECOND);repaint();}}}//定义时钟类class MyTimerimplements TimerListener{//定义时钟类的属性static int intHour,intMinute,intSecond;//构造函数public MyTimer(){setCurrentTimeAsSystemTime();Timer t = new Timer(1000, this); //实例Timer类,里面有run 方法t.start();}//显示当前时间public void displayCurrentTime(){JOptionPane.showMessageDialog(null,intHour+":"+intMinute+":"+intSecond);}//设定当前时间public void setCurrentTime(){//从对话框输入时,分秒String strTemp=JOptionPane.showInputDialog(null,"请输入当前小时(24小时制):"); int iHour=Integer.parseInt(strTemp);strTemp=JOptionPane.showInputDialog(null,"请输入当前分:");int iMinute=Integer.parseInt(strTemp);strTemp=JOptionPane.showInputDialog(null,"请输入当前秒:");int iSecond=Integer.parseInt(strTemp);//设定当前时间为对话框输入的时间if(iHour>=0&&iHour<24)intHour=iHour;else intHour=0;if(iMinute>=0&&iMinute<60)intMinute=iMinute;else intMinute=0;if(iSecond>=0&&iSecond<60)intSecond=iSecond;MyTimer1.count++;// ClockCanvas.seconds=iHour*60*60+iMinute*60+iSecond;}//设定当前时间为系统时间,构造函数调用public void setCurrentTimeAsSystemTime(){//定义Date类的一个对象,用来获取系统时间Date timeCurrent=new Date();//将系统的时,分秒设定为当前时间intHour=timeCurrent.getHours(); intMinute=timeCurrent.getMinutes(); intSecond=timeCurrent.getSeconds(); } //走时public void timeElapsed(Timer t){//系统走时intSecond++;if (intSecond==60){intMinute++;intSecond=0;}if (intMinute==60){intHour++;intMinute=0;}if (intHour==24){intHour=0;}}}interface TimerListener //接口了{void timeElapsed(Timer t);}class Timer extends Thread //类啊{private TimerListener target;private int interval;public Timer(int i, TimerListener t){target = t;interval = i;setDaemon(true); //Thread 里面方法目的跟着老大走 } public void run(){ try{while (!interrupted()){sleep(interval);target.timeElapsed(this);}}catch(InterruptedException e) {}}}。
利用JAVA实现一个时钟的小程序
JAVA课程项目报告项目题目:利用JAVA实现一个小时钟的程序专业班级:10软件工程利用JAVA实现一个时钟的小程序1.软件开发的需求分析在当今的信息时代,时钟已经成为人们生活中必不可少的应用工具,Java语言是当今流行的网络编程语言,它具有面向对象、与平台无关、安全、多线程等特点。
使用Java 语言不仅可以实现大型企业级的分布式应用系统,还能够为小型的、嵌入式设备进行应用程序的开发。
面向对象的开发方法是当今世界最流行的开发方法,它不仅具有更贴近自然的语义,而且有利于软件的维护和继承。
为了进一步巩固课堂上所学到的知识,深刻把握Java语言的重要概念及其面向对象的特性,锻炼我们熟练的应用面向对象的思想和设计方法解决实际问题的能力,开设了Java程序设计课程设计。
此次课程设计的题目为简单的小时钟程序设计,通过做巩固所学Java语言基本知识,增进Java语言编辑基本功,掌握JDK、JCreator等开发工具的运用,拓宽常用类库的应用。
使我们通过该教学环节与手段,把所学课程及相关知识加以融会贯通,全面掌握Java语言的编程思想及面向对象程序设计的方法,为今后从事实际工作打下坚实的基础。
2.具体实现2.1设计思路Java是一种简单的,面向对象的,分布式的,解释的,键壮的,安全的,结构中立的,可移植的,性能很优异的,多线程的,动态的语言。
Java去掉了C++语言的许多功能,让Java的语言功能很精炼,并增加了一些很有用的功能,如自动收集碎片。
这将减少平常出错的50%。
而且,Java很小,整个解释器只需215K的RAM。
因此运用JAVA程序编写小时钟程序,实现简单显示时间的功能。
本次课程设计做的是Java简单小时钟,它是图形界面、线程、流与文件等技术的综合应用,其界面主要采用了java.awt包,javax.swing包等。
程序实现了小时钟的基本功能。
2.2设计方法在设计简单小时钟时,需要编写5个Java源文件:Server.java、Objecting.java、LogIn.java、ClientUser.java、Client.java。
java简易流动字幕代码(用电子时钟控制)
import java.awt.*;import java.awt.event.*;import java.text.SimpleDateFormat;import java.util.Date;import javax.swing.*;public class Ticker_Tape extends JFrame {private Date now=new Date();private Panel buttons=new Panel();private Button button_start=new Button("启动");private Button button_interrupt=new Button("停止");private Clock time=new Clock();private Label word=new Label("Welcom");char space[]=new char[75];public Ticker_Tape(){super("滚动字");this.setBounds(300,240,300,200);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.setLayout(new GridLayout(3,1));this.add(word);this.add(time);this.add(buttons);buttons.setLayout(new FlowLayout());buttons.add(button_start);buttons.add(button_interrupt);java.util.Arrays.fill(space, ' '); //将字符数组space填充满空格word.setText(new String(space)+word.getText()); //text前加空格字符串 setVisible(true);}private class Clock extends Label implements ActionListener, Runnable{ private Thread clocker=null;private Date now=new Date();public Clock(){b utton_start.addActionListener(this);button_interrupt.addActionListener(this);S impleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");//可以方便地修改日期格式S tring t = dateFormat.format(now );t his.setText(t);}public void start(){if(clocker==null){clocker=new Thread(this);clocker.start();}}public void stop(){clocker=null;}public void run(){Thread currentThread=Thread.currentThread();while(clocker==currentThread){now=new Date();SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");//可以方便地修改日期格式String t = dateFormat.format( now );this.setText(t);try{String str =word.getText();str = str.substring(1)+ str.substring(0,1);word.setText(str);clocker.sleep(1000);}catch(InterruptedException ie){JOptionPane.showMessageDialog(this,"Thread error:+ie");}}}public void actionPerformed(ActionEvent e){if (e.getSource()==button_start) {clocker = new Thread(this); //重新创建一个线程对象clocker.start();button_start.setEnabled(false);button_interrupt.setEnabled(true);}if (e.getSource()==button_interrupt) //单击中断按钮时{clocker.stop(); //设置当前线程对象停止标记button_start.setEnabled(true);button_interrupt.setEnabled(false);}}}//内部类结束public static void main(String[] args) { Ticker_Tape time=new Ticker_Tape(); }}运行结果:。
电子时钟java写的
电子时钟java写的package com.lw;import java.awt.BorderLayout;import java.awt.EventQueue;import java.awt.Font;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.util.Calendar;import java.util.GregorianCalendar;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.SwingConstants;import javax.swing.UIManager;import javax.swing.border.EmptyBorder;public class DigitalClock extends JFrame {/****/private static final long serialV ersionUID = 4962111797317773666L;private JPanel contentPane;private JLabel label;/*** Launch the application.*/public static void main(String[] args) {try {UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");} catch (Throwable e) {e.printStackTrace();}EventQueue.invokeLater(new Runnable() {public void run() {try {DigitalClock frame = new DigitalClock();frame.setV isible(true);} catch (Exception e) {e.printStackTrace();}}});}/*** Create the frame.*/public DigitalClock() {addWindowListener(new WindowAdapter() {@Overridepublic void windowActivated(WindowEvent e) {do_this_windowActivated(e);}});setTitle("\u6570\u5B57\u65F6\u949F");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setBounds(100, 100, 200, 100);contentPane = new JPanel();contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));contentPane.setLayout(new BorderLayout(0, 0));setContentPane(contentPane);label = new JLabel("New label");label.setFont(new Font("微软雅黑", Font.BOLD, 20));label.setHorizontalAlignment(SwingConstants.CENTER);contentPane.add(label, BorderLayout.CENTER);}private String format(int number) {return number < 10 ? "0" + number : "" + number;// 如果数字小于10就在其前面加0补齐}private String getTime() {Calendar calendar = new GregorianCalendar();int hour = calendar.get(Calendar.HOUR_OF_DAY); // 获得当前小时int minute = calendar.get(Calendar.MINUTE); // 获得当前分钟int second = calendar.get(Calendar.SECOND); // 获得当前秒return format(hour) + ":" + format(minute) + ":" + format(second);// 返回格式化的字符串}protected void do_this_windowActivated(WindowEvent e) { new Thread() {public void run() {while (true) {// 让时钟一直处于更新状态label.setText(getTime()); // 更新时钟try {Thread.sleep(1000); // 休眠一秒钟} catch (InterruptedException e) {e.printStackTrace();}}};}.start(); }}。
java时钟,带修改时间的功能
package com.newer.clock;import java.awt.Color;import java.awt.Graphics;import java.awt.Point;import java.util.Calendar;import javax.swing.JPanel;class C extends JPanel implements Runnable {private Point origin = new Point(500, 200);// 设置圆心点的坐标private int arch, arcm, arcs;// 定义了三个角度的变量/*** 定义了hour, minute, second三个变量,从arcs = 360 - (second - 15) * 6; arcm = 360* - (minute - 15) * 6; arch = (360 - (hour * 5 - 15) * 6)-(minute/6)*3;* 可以判断出是为了把系统当前时间初始化给这三个变量,并转化成角度*/int hour, minute, second;Calendar cal = null;/*** 构造方法c是为了实现获取系统当前时间,并分别赋值给hour, minute, second 三个变量,然后转换成角度(总的是为了实现角度和* hour, minute, second的用处)*/public C() {/*** 获取系统当前时间的年月日,小时,分钟,秒,并复制给变量*/cal = Calendar.getInstance();// 用于表示日历的设置cal.setTime(new java.util.Date());hour = cal.get(Calendar.HOUR); // 获取日历上的小时// int text1 = 0;// cal.getTime(text1);// cal.set(hour, text1);minute = cal.get(Calendar.MINUTE);second = cal.get(Calendar.SECOND);/*** 创建线程,线程是为了实现钟表里的针每个多久转一下*/Thread thread = new Thread(this);/*** 把三个变量hour, minute, second转化成角度*/arcs = 360 - (second - 15) * 6; // 15秒时等于0度arcm = 360 - (minute - 15) * 6;arch = (360 - (hour * 5 - 15) * 6) - (minute / 6) * 3; thread.start();// 开始线程}public void setTime(Calendar cal){if(cal == null) return;hour = cal.get(Calendar.HOUR);minute = cal.get(Calendar.MINUTE);second = cal.get(Calendar.SECOND);arcs = 360 - (second - 15) * 6;arcm = 360 - (minute - 15) * 6;arch = (360 - (hour * 5 - 15) * 6) - (minute / 6) * 3;}public Calendar getCurrentTime(){return cal;}/*** 重写窗体*/@Override/*** 实现画线,画刻度(一个钟,* 要有刻度,针,圆等,这些需要画上的)*/protected void paintComponent(Graphics g) {super.paintComponent(g);this.setBackground(Color.GRAY);g.drawOval(375, 75, 250, 250);g.drawOval(375, 76, 251, 250);g.drawOval(375, 77, 252, 250);for (int i = 0; i < 60; i++) {/*** 几点与几点之间的刻度划分*/if (i % 5 == 0)g.setColor(Color.RED);// 设置秒针的颜色/*** 画秒针的线*/g.drawLine(origin.x + ((int) (0.95 * 120 * Math.cos((6 * i) * Math.PI / 180))),origin.y + ((int) (-120 * 0.95 * Math.sin((6 * i) * Math.PI/ 180))),origin.x + ((int) (120 * 1.05 * Math.cos((6 * i) * Math.PI / 180))),origin.y + ((int) (-120 * 1.05 * Math.sin((6 * i) * Math.PI / 180))));g.setColor(Color.BLACK);}g.fillRect(origin.x+ ((int) (0.95 * 120 * Math.cos(90 * Math.PI / 180) - 3)), origin.y+ ((int) (-120 * 0.92 * Math.sin(90 * Math.PI / 180) - 16)), 6, 18);g.fillRect(origin.x+ ((int) (0.95 * 120 * Math.cos(270 * Math.PI / 180) - 3)), origin.y+ ((int) (-120 * 0.92 * Math.sin(270 * Math.PI / 180))), 6, 18);g.fillRect(origin.x + ((int) (0.92 * 120 * Math.cos(0 * Math.PI / 180))), origin.y+ ((int) (-120 * 0.97 * Math.sin(0 * Math.PI / 180) - 3)), 18, 6);g.fillRect(origin.x// 0.92是移动刻度的位置+ ((int) (0.92 * 120 * Math.cos(180 * Math.PI / 180) - 16)), origin.y+ ((int) (-120 * 0.97 * Math.sin(180 * Math.PI / 180) - 3)), 18, 6);//g.setFont(new Font("宋体", Font.BOLD, 20));g.drawString("12",origin.x+ ((int) (0.8 * 120 * Math.cos(90 * Math.PI / 180) - 12)), origin.y + ((int) (-120 * 0.8 * Math.sin(90 * Math.PI / 180))));g.drawString("3",origin.x + ((int) (0.8 * 120 * Math.cos(0 * Math.PI / 180))), origin.y+ ((int) (-120 * 0.8 * Math.sin(0 * Math.PI / 180) + 8))); g.drawString("6",origin.x+ ((int) (0.8 * 120 * Math.cos(270 * Math.PI / 180) - 6)),origin.y+ ((int) (-120 * 0.8 * Math.sin(270 * Math.PI / 180) + 10)));g.drawString("9",origin.x+ ((int) (0.8 * 120 * Math.cos(180 * Math.PI / 180) - 8)),origin.y+ ((int) (-120 * 0.8 * Math.sin(180 * Math.PI / 180) + 8)));g.setColor(Color.RED);g.drawLine(origin.x, origin.y,origin.x + ((int) (120 * Math.cos((arcs) * Math.PI / 180))),origin.y + ((int) (-120 * Math.sin((arcs) * Math.PI / 180))));g.setColor(Color.GREEN);g.drawLine(origin.x, origin.y,origin.x + ((int) (90 * Math.cos((arcm) * Math.PI / 180))),origin.y + ((int) (-90 * Math.sin((arcm) * Math.PI / 180))));g.setColor(Color.BLACK);g.drawLine(origin.x, origin.y,origin.x + ((int) (60 * Math.cos((arch) * Math.PI / 180))),origin.y + ((int) (-60 * Math.sin((arch) * Math.PI / 180))));g.drawString(cal.getTime().toString(), 30, 20);// 文字的显示}/*** 重写接口,实现钟表的转动*/@Override/***普通方法,实现钟表的转动*/public void run() {/*** while循环的作用,打个比方:时钟上的0点就是12点,同时是为了实现归0 */while (true) {if (arcs == 0)arcs = 360;if (arcm == 0)arcm = 360;if (arch == 0)arch = 360;/*** try是为了实现钟表转动的核心代码*/try {/*** 线程每1秒,停一下,等于秒针转动一下*/Thread.sleep(1000);/*** 实现时分秒三个针的走动*/arcs = Math.abs(arcs - 6) % 360;// 走到下一刻的角度位置if (arcs == 90)arcm = Math.abs(arcm - 6) % 360;if ((arcm - 54) % 36 == 0 && arcs == 90)arch = Math.abs(arch - 3) % 360;}/*** 处理异常问题的代码*/catch (InterruptedException e) {e.printStackTrace();}this.repaint();// 异常处理完后,重亲执行核心代码和重画}}}package com.newer.clock;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.GridLayout;import java.awt.Point;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.Calendar;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;import javax.swing.JTextField;// 这是功能键的添加及窗体的设置public class Clock extends JFrame implements ActionListener { private static final long serialV ersionUID = 2143849358452364853L; private JMenuBar bar = new JMenuBar();private JMenu menu1 = new JMenu("功能");private JMenu menu2 = new JMenu("关于");private JMenuItem item1 = new JMenuItem("设定时间");private JMenuItem item2 = new JMenuItem("闹钟");private JMenuItem item3 = new JMenuItem("时区");private C cPanel = null;public Clock() {cPanel = new C();this.add(cPanel);this.setTitle("经典时钟");this.setSize(600, 400);this.setV isible(true);this.setJMenuBar(bar);bar.add(menu1);bar.add(menu2);menu1.add(item1);menu1.add(item2);menu1.add(item3);item1.addActionListener(this);}public static void main(String[] args) {Clock dlg = new Clock();dlg.setLocation(300, 130);// 桌面位置dlg.setSize(850, 450);// 长宽dlg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);dlg.setV isible(true);}@Overridepublic void actionPerformed(ActionEvent e) {if (e.getSource().equals(item1)) {System.out.println("点击鼠标,设置时间!");SetupDialog setupdialog = new SetupDialog(cPanel);setupdialog.show();}}}package com.newer.clock;import java.awt.BorderLayout;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.Calendar;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;class SetupDialog extends JDialog implements ActionListener{private JPanel panel1 = new JPanel();private JPanel panel2 = new JPanel();private JLabel label1 = new JLabel("时钟:");private JLabel label2 = new JLabel("分钟:");private JLabel label3 = new JLabel("秒钟:");private JTextField hour = new JTextField();private JTextField minute = new JTextField();private JTextField second = new JTextField();static JButton button1 = new JButton("确定");static JButton button2 = new JButton("取消");C cPanel = null;SetupDialog(C cPanel) {this.iuit();this.setTitle("设置");this.setSize(300, 100);this.setV isible(true);this.cPanel = cPanel;button1.addActionListener( this);button2.addActionListener(this);// button1.addActionListener(new ActionListener() {// public void actionPerformed(ActionEvent e) {// int h = Integer.parseInt(hour.getText() == null ? "0" : hour.getText());// int m = Integer.parseInt(minute.getText() == null ? "0" : minute.getText()); // int s = Integer.parseInt(second.getText() == null ? "0" : second.getText());// Calendar curTime = SetupDialog.this.cPanel.getCurrentTime();// curTime.set(Calendar.HOUR, h);// curTime.set(Calendar.MINUTE, h);// curTime.set(Calendar.SECOND, s);// SetupDialog.this.cPanel.setTime(curTime);// SetupDialog.this.cPanel.repaint();// }// });}public void iuit() {this.setLayout(new BorderLayout());this.add(panel1, BorderLayout.CENTER);this.add(panel2, BorderLayout.SOUTH);panel1.setLayout(new GridLayout(2, 3));panel1.add(label1);panel1.add(label2);panel1.add(label3);panel1.add(hour);panel1.add(minute);panel1.add(second);panel2.add(button1);panel2.add(button2);}@Overridepublic void actionPerformed(ActionEvent e) {if (e.getSource().equals(button1)){int h = Integer.parseInt(hour.getText() == null ? "0" : hour.getText());int m = Integer.parseInt(minute.getText() == null ? "0" : minute.getText());int s = Integer.parseInt(second.getText() == null ? "0" : second.getText());Calendar curTime = SetupDialog.this.cPanel.getCurrentTime();curTime.set(Calendar.HOUR, h);curTime.set(Calendar.MINUTE, h);curTime.set(Calendar.SECOND, s);SetupDialog.this.cPanel.setTime(curTime);SetupDialog.this.cPanel.repaint();}else if(e.getSource().equals(button2)){this.dispose();}}}。
java程序 时钟
第一步:新建一个WinForm的工程,添加一个UserControl的派生类取名ClockControl. 第二步:DoubleBuffered属性设为true, 防止闪烁,也可以自己用MemBitmap来做,不过.NET提供了方便的DoubleBuffered,这点比C++好方便太多了。
第三步:添加一个Timer,定时时间为1000(1 Second),即每秒刷新一次,取当前的时间。
Timer的Tick事件代码如下:private void clockTimer_Tick(object sender, EventArgs e){Invalidate();}第四步:Overright OnPaint 直接看代码吧protected override void OnPaint(PaintEventArgs e){Graphics g = e.Graphics;// init the origing.TranslateTransform(this.Width / 2.0f, this.Height / 2.0f);int dialRadius = Math.Min(this.Width, this.Height) / 2;// Draw the clock dialGraphicsState state = g.Save();for (int i = 0; i<60; i++){int radius = 15;if (i % 5 == 0)radius = 25;g.FillEllipse(Brushes.Blue, new Rectangle(-radius / 2, -dialRadius, radius, r adius));g.RotateTransform(360 / 60);}g.Restore(state);// Get current timeDateTime now = DateTime.Now;// Draw hour handstate = g.Save();g.RotateTransform((Math.Abs(now.Hour - 12) + now.Minute / 60f ) * 360f / 12f);g.FillRectangle(Brushes.Black, new Rectangle(-5, -dialRadius + 50, 10, dialR adius - 40));g.Restore(state);// Draw Minute handstate = g.Save();g.RotateTransform((now.Minute + now.Second / 60f) * 360f / 60f);g.FillRectangle(Brushes.DarkGreen, new Rectangle(-3, -dialRadius + 30, 6, d ialRadius - 15));g.Restore(state);// Draw Second handstate = g.Save();g.RotateTransform(now.Second * 360f / 60f);g.FillRectangle(Brushes.Red, new Rectangle(-1, -dialRadius + 10, 2, dialRadi us));g.Restore(state);}简单说明一下,这个Control主要使用GDI+的Transform函数,用g.TranslateTransform(this.Width / 2.0f, this.Height / 2.0f);把坐标原点移动到中心,使用RotateTransform来旋转角度实现时钟的表皮和指针的不同位置。
JavaFX实现简易时钟效果(一)
JavaFX实现简易时钟效果(⼀)本⽂实例为⼤家分享了JavaFX实现简易时钟效果的具体代码,供⼤家参考,具体内容如下效果图⽤当前时间创建时钟,绘制表盘。
钟表是静⽌的。
让指针动起来,请参照:主函数⽂件 ShowClock:package primier;import javafx.application.Application;import javafx.geometry.Insets;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.stage.Stage;import javafx.scene.paint.Color;import yout.*;import javafx.scene.control.*;import javafx.scene.image.Image;import javafx.scene.image.ImageView;import javafx.scene.shape.Line;public class ShowClock extends Application {@Override //Override the start method in the Application classpublic void start(Stage primaryStage) {// 创建时钟⾯板ClockPane clock = new ClockPane();// 当前时间整理为字符串String timeString = clock.getHour() + ":" + clock.getMinute()+ ":" + clock.getSecond();Label lbCurrentTime = new Label(timeString);BorderPane pane = new BorderPane();pane.setCenter(clock);pane.setBottom(lbCurrentTime);// 将时钟字符串设为靠上居中BorderPane.setAlignment(lbCurrentTime, Pos.TOP_CENTER);Scene scene = new Scene(pane, 250,250);primaryStage.setTitle("Display Clock");primaryStage.setScene(scene);primaryStage.show();}public static void main (String[] args) {unch(args);}}ClockPane 类package primier;import java.util.Calendar;import java.util.GregorianCalendar;import yout.Pane;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.shape.Line;import javafx.scene.text.Text;public class ClockPane extends Pane {private int hour;private int minute;private int second;// 时钟⾯板的宽度和⾼度private double w = 250, h = 250;/** ⽤当前时间创建时钟 */public ClockPane() {setCurrentTime();}/** Return hour */public int getHour() { return hour; }/** Return minute */public int getMinute() { return minute; }/** Return second */public int getSecond() { return second; }/** Set the current time for the clock */public void setCurrentTime() {// ⽤当前时间创建Calendar类Calendar calendar = new GregorianCalendar();this.hour = calendar.get(Calendar.HOUR_OF_DAY);this.minute = calendar.get(Calendar.MINUTE);this.second = calendar.get(Calendar.SECOND);paintClock();}/** 绘制时钟 */protected void paintClock() {double clockRadius = Math.min(w,h)*0.4; // 时钟半径// 时钟中⼼x, y坐标double centerX = w/2;double centerY = h/2;// 绘制钟表Circle circle = new Circle(centerX, centerY, clockRadius);circle.setFill(Color.WHITE); // 填充颜⾊circle.setStroke(Color.BLACK); // 笔画颜⾊Text t1 = new Text(centerX-5, centerY-clockRadius+12,"12");Text t2 = new Text(centerX-clockRadius+3, centerY +5, "9");Text t3 = new Text(centerX+clockRadius-10, centerY+3, "3");Text t4 = new Text(centerX-3, centerY+clockRadius-3,"6");// 秒针double sLength = clockRadius * 0.8;double secondX = centerX + sLength * Math.sin(second * (2 * Math.PI / 60)); double secondY = centerY - sLength * Math.cos(second * (2 * Math.PI / 60)); Line sLine = new Line(centerX, centerY, secondX, secondY);sLine.setStroke(Color.GRAY);// 分针double mLength = clockRadius * 0.65;double minuteX = centerX + mLength * Math.sin(minute * (2 * Math.PI / 60)); double minuteY = centerY - mLength * Math.cos(minute * (2 * Math.PI / 60)); Line mLine = new Line(centerX, centerY, minuteX, minuteY);mLine.setStroke(Color.BLUE);// 时针double hLength = clockRadius * 0.5;double hourX = centerX + hLength *Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12));double hourY = centerY - hLength *Math.cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12));Line hLine = new Line(centerX, centerY, hourX, hourY);sLine.setStroke(Color.GREEN);// 将之前的结点清空,绘制新创建的结点getChildren().clear();getChildren().addAll(circle, t1, t2, t3, t4, sLine, mLine, hLine);}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
Java数字时钟(简单的桌面应用)
import java.util.*;/*****该程序是一个简单的数字时钟,每变化一秒,颜色随机变色,可以系统托盘,最大的特点是可以和桌面形成一体,也就是容纳这个数字时钟的窗体可以看成是透明的***********/import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.awt.image.BufferedImage;public class app509 extends JFrame{static int i=-1,geli=-1;/*这一部分是系统托盘图标的文件路径,可以自己设置,只要路径正确即可,可以是gif,jpg,png格式*/static Image image=Toolkit.getDefaultToolkit().getImage("D:1\\3.png");static SystemTray systemTray=SystemTray.getSystemTray();static PopupMenu pop01=new PopupMenu();static MenuItem MI01=new MenuItem("打开主程序");static MenuItem MI02=new MenuItem("退出程序");static MenuItem MI03=new MenuItem("隐藏");static TrayIcon trayIcon=new TrayIcon(image,"这是程序图标",pop01);static JLabel beijingtu=new JLabel();static JLabel xingqi=new JLabel(" ",JLabel.CENTER);static JLabel jlabel02=new JLabel("年",JLabel.CENTER);static JLabel jlabel03=new JLabel("月",JLabel.CENTER);static JLabel jlabel04=new JLabel("日",JLabel.CENTER);static JLabel jlabel05=new JLabel("分",JLabel.CENTER);static JLabel jlabel10=new JLabel("时",JLabel.CENTER);static JLabel jlabel12=new JLabel("分",JLabel.CENTER);static JLabel jlabel13=new JLabel("秒",JLabel.CENTER);static JLabel jlabel06=new JLabel(" ",JLabel.CENTER);static JLabel jlabel07=new JLabel(" ",JLabel.CENTER);static JLabel jlabel08=new JLabel(" ",JLabel.CENTER);static JLabel jlabel09=new JLabel(" ",JLabel.CENTER);static JLabel jlabel11=new JLabel(" ",JLabel.CENTER);static JLabel jlabel=new JLabel(" ",JLabel.CENTER);static JLabel jbData[]={jlabel13,jlabel02,jlabel03,jlabel04,jlabel10,jlabel12};static JLabel jbData02[]={jlabel,jlabel07,jlabel08,jlabel09,jlabel11,jlabel06};static int mill=0;static int minute=0;static int hour=0;static int day=0;static int month=0;static int year=0;static int week;static int zuobiaoX,zuobiaoY;static JFrame JF01=new JFrame();static JDialog JF=new JDialog(JF01," ");static Robot robot;static BufferedImage image1;static Rectangle rec;static class mouseListener extends MouseAdapter{public void mouseClicked(MouseEvent a){if(a.getSource()==trayIcon){if(a.getClickCount()==2){i++;if(i%2==1){geli++;if(geli%2==1){image1=robot.createScreenCapture(rec);beijingtu.setIcon(new ImageIcon(image1));JF.setBounds(0,0,120,560);JF.setVisible(true);}}else{JF.setBounds(0,0,400,1);}}}}public void mouseEntered(MouseEvent a){if(a.getSource()==JF){image1=robot.createScreenCapture(rec);beijingtu.setIcon(new ImageIcon(image1));JF.setBounds(0,0,120,560);JF.setVisible(true);}}public void mouseExited(MouseEvent a){if(a.getSource()==JF){JF.setBounds(0,0,400,1);}}}public static void main(String args[]) throws Exception{trayIcon.addMouseListener(new mouseListener());rec=new Rectangle(0,0,(int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(),(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight());try{robot=new Robot(); }catch(Exception b){}image1=robot.createScreenCapture(rec);beijingtu.setIcon(new ImageIcon(image1));MI01.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent a){Image1=robot.createScreenCapture(rec);beijingtu.setIcon(new ImageIcon(image1));JF.setBounds(0,0,120,560);JF.setVisible(true);}});MI03.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent a){JF.setBounds(0,0,400,1);}});MI02.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent a){System.exit(0);}});try{pop01.add(MI01);pop01.add(MI03);pop01.add(MI02);systemTray.add(trayIcon);trayIcon.setImageAutoSize(true);trayIcon.addMouseListener(new mouseListener());}catch(Exception a){} JF.setResizable(false) ;JF.addMouseListener(new mouseListener());JF.setUndecorated(true);beijingtu.setBounds(0,0,(int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(),(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight());JF.setLayout(null);JF.setBounds(0,0,120,560);JF.setVisible(true);jlabel02.setBounds(91,94,24,25);jlabel06.setBounds(15,94,64,28);jlabel03.setBounds(91,175,24,25);jlabel07.setBounds(2,125,86,75);jlabel04.setBounds(91,261,24,25);jlabel08.setBounds(2,210,86,75);jlabel10.setBounds(91,346,24,25);jlabel09.setBounds(2,296,86,75);jlabel11.setBounds(2,382,86,75);jlabel12.setBounds(91,433,24,25);jlabel13.setBounds(91,520,24,25);jlabel.setBounds(2,468,86,75);xingqi.setBounds(2,30,118,62);JF.add(xingqi);xingqi.setHorizontalTextPosition(JLabel.CENTER);xingqi.setFont(new Font("微软雅黑",Font.BOLD,20));for(int i=0;i<jbData.length;i++){JF.add(jbData[i]);JF.add(jbData02[i]);}for(int i=0;i<jbData.length;i++){jbData[i].setFont(new Font("微软雅黑",Font.BOLD,15));jbData02[i].setFont(new Font("微软雅黑",Font.BOLD,30));}jlabel06.setFont(new Font("微软雅黑",Font.BOLD,15));for(int i=0;i<jbData.length;i++){jbData[i].setForeground(Color.blue);jbData02[i].setForeground(Color.red);}for(int i=0;i<jbData.length;i++){jbData[i].setHorizontalTextPosition(JLabel.CENTER);jbData02[i].setHorizontalTextPosition(JLabel.CENTER);}jlabel02.setHorizontalTextPosition(JLabel.RIGHT);JF.add(beijingtu);xiancheng xiancheng01=new xiancheng();xiancheng01.start();}}class xiancheng extends Thread{static GregorianCalendar date=new GregorianCalendar();app509 app=new app509();public void run(){for(int i=0;i<60;){try{sleep(1000);}catch(Exception a){}app.year=(date=new GregorianCalendar()).get(date.YEAR);app.jlabel06.setText(Integer.toString(app.year));app.month=((date=new GregorianCalendar()).get(date.MONTH)+1);app.jlabel07.setText(Integer.toString(app.month));app.day=(date=new GregorianCalendar()).get(date.DAY_OF_MONTH);app.jlabel08.setText(Integer.toString(app.day));app.week=(date=new GregorianCalendar()).get(date.DAY_OF_WEEK);app.hour=(date=new GregorianCalendar()).get(date.HOUR_OF_DAY);app.jlabel09.setText(Integer.toString(app.hour));app.minute=(date=new GregorianCalendar()).get(date.MINUTE);app.jlabel11.setText(Integer.toString(app.minute));l=(date=new GregorianCalendar()).get(date.SECOND);app.jlabel.setText(Integer.toString(l));if(app.jlabel.getText()!=" "){app.xingqi.setForeground(new Color((int)(255*Math.random()),(int)(255*Math.random()),(int)(255*Math.random())));for(int j=0;j<app.jbData.length;j++){app.jbData[j].setForeground(new Color((int)(255*Math.random()),(int)(255*Math.random()),(int)(255*Math.random())));app.jbData02[j].setForeground(new Color((int)(255*Math.random()),(int)(255*Math.random()),(int)(255*Math.random())));}} switch(app.week){case 1 : app.xingqi.setText("星期日");break;case 2 : app.xingqi.setText("星期一");break;case 3 : app.xingqi.setText("星期二");break;case 4 : app.xingqi.setText("星期三");break;case 5 : app.xingqi.setText("星期四");break;case 6 : app.xingqi.setText("星期五");break;case 7 : app.xingqi.setText("星期六");break;}System.gc();}}}/****复制以上代码进行编译即可*****/程序效果图:。
利用javafx编写一个时钟制作程序
利⽤javafx编写⼀个时钟制作程序1.⾸先创建⼀个时钟类,⽤于编写时钟的各种特有属性package javaclock;/**** @author admin*/import java.util.Calendar;import java.util.GregorianCalendar;import java.util.Scanner;import yout.Pane;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.shape.Line;import javafx.scene.text.Text;import javafx.scene.control.Button;public class ClockPane extends Pane{private int hour;private int minute;private int second;private double w = 250,h = 250;//⽆参构造函数public ClockPane() {setCurrentTime();//调⽤⽅法}//有参构造函数public ClockPane(int hour,int minute,int second) {// Button btn = new Button("调整时间");//btn.setCurrentTime1();this.hour = hour;this.minute = minute;this.second = second;paintClock();//调⽤⽅法}//set与get⽅法public int getHour() {return hour;}public void setHour(int hour) {this.hour = hour;paintClock();}public int getMinute() {return minute;}public void setMinute(int minute) {this.minute = minute;paintClock();}public int getSecond() {return second;}public void setSecond(int second) {this.second = second;paintClock();}public double getW() {return w;}public void setW(double w) {this.w = w;paintClock();}public double getH() {return h;}public void setH(double h) {this.h = h;paintClock();}//修改当前时间public void setCurrentTime1(int hour,int minute,int second){this.hour = hour;this.minute = minute;this.second = second;paintClock();}//⽅法setCurrentTime()设置获取当前时间public void setCurrentTime() {Calendar calendar = new GregorianCalendar();//多态this.hour = calendar.get(Calendar.HOUR_OF_DAY);//获取⼩时this.minute = calendar.get(Calendar.MINUTE);//获取分钟this.second = calendar.get(Calendar.SECOND);//获取秒paintClock();}//创建paintClock()显⽰时间public void paintClock() {double clockRadius = Math.min(w, h)*0.8*0.5;//时钟半径double centerX = w/2;//圆⼼坐标double centerY = h/2;//创建时钟圆形Circle circle = new Circle(centerX,centerY,clockRadius);//创建圆circle.setFill(Color.WHITE);//圆形背景⾊为⽩⾊circle.setStroke(Color.BLACK);//圆形边缘⾊为⿊⾊//创建四个⽂本对象⽤于将12,9,6,3填⼊圆形中,注意不要压在圆形上⾯,需要计算坐标Text text1 = new Text(centerX-5,centerY-clockRadius+12,"12");Text text2 = new Text(centerX-clockRadius+3,centerY+5,"9");Text text3 = new Text(centerX+clockRadius-10,centerY+3,"3");Text text4 = new Text(centerX-3,centerY+clockRadius-3,"6");//分别绘制时针,分针,秒针//秒针double secLength = clockRadius*0.8;//秒针长度double secondX = centerX + secLength*Math.sin(second*(2*Math.PI/60));//因为⼀分钟有60秒,故求出当前秒针的⾓度,利⽤三⾓函数公式即可计算出秒针的端点x坐标double secondY = centerY - secLength*Math.cos(second*(2*Math.PI/60));//同理求出秒针的端点Y坐标Line secline = new Line(centerX,centerY,secondX,secondY);//创建线段对象实现秒针secline.setStroke(Color.RED);//将秒针定义为红⾊//分针double minLength = clockRadius*0.65;//分针长度double minuteX = centerX + minLength*Math.sin((minute )*(2*Math.PI/60));//因为⼀⼩时有六⼗分钟,利⽤分针的时间加上秒针的时间,利⽤三⾓函数对应的⾓度,即可计算出分针的端点x坐标double minuteY = centerY - minLength*Math.cos((minute )*(2*Math.PI/60));//同理求出分针的端点Y坐标Line minline = new Line(centerX,centerY,minuteX,minuteY);//创建线段对象实现秒针minline.setStroke(Color.GREEN);//将秒针定义为绿⾊//时针double houLength = clockRadius*0.5;//时针长度double hourX = centerX + houLength*Math.sin((hour%12 + minute/60.0 )*(2*Math.PI/12));//因为⼀天有⼗⼆⼩时,⼀⼩时有六⼗分钟,利⽤⼩时的时间加上分针的时间再加上秒针的时间,利⽤三⾓函数对应的⾓度,即可计算出分针的端点x坐标double hourY = centerY - houLength*Math.cos((hour%12 + minute/60.0 )*(2*Math.PI/12));//同理求出时针的端点Y坐标Line houline = new Line(centerX,centerY,hourX,hourY);//创建线段对象实现时针houline.setStroke(Color.BLUE);//将秒针定义为蓝⾊getChildren().clear();//每调⽤执⾏⼀次paintClock()⽅法就会清空⾯板getChildren().addAll(circle,text1,text2,text3,text4,secline,minline,houline);//将⼏个控件添加到⾯板中}}2、然后编写⼀个测试类,⽤于通过多线程创建呈现时钟的动画效果/** To change this license header, choose License Headers in Project Properties.* To change this template file, choose Tools | Templates* and open the template in the editor.*/package javaclock;import java.util.*;import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Button;import yout.StackPane;import javafx.stage.Stage;import yout.BorderPane;import javafx.animation.Timeline;import bel;import javafx.animation.KeyFrame;import javafx.geometry.Pos;import javafx.util.Duration;import yout.HBox;import yout.VBox;/**** @author admin*/public class JavaClock extends Application {//JavaClock jc = new JavaClock();ClockPane clock = new ClockPane();//BorderPane borderPane = new BorderPane();//@Overridepublic void start(Stage primaryStage) throws Exception {// TODO ⾃动⽣成的⽅法存根//绑定事件源EventHandler<ActionEvent> eventHandler = e ->{clock.setCurrentTime();String timeString = clock.getHour()+":"+clock.getMinute()+":"+clock.getSecond();Label labelCurrentTime = new Label(timeString);borderPane.setCenter(clock);borderPane.setBottom(labelCurrentTime);BorderPane.setAlignment(labelCurrentTime, Pos.TOP_CENTER);};Timeline animation = new Timeline(new KeyFrame(lis(1000),eventHandler));//设定时钟动画每1秒变⼀次,关键帧时间间隔animation.setCycleCount(Timeline.INDEFINITE);animation.play();//SceneScene scene = new Scene(borderPane,250,250);primaryStage.setTitle("JavaClock");primaryStage.setScene(scene);primaryStage.show();//展⽰场景borderPane.widthProperty().addListener(o->clock.setW(borderPane.getWidth()));//保持时间⾯板与场景同步borderPane.heightProperty().addListener(o->clock.setH(borderPane.getHeight()));//设置⼀个按钮,⽤于调整时间}/*** @param args the command line arguments */public static void main(String[] args) { launch(args);}}。
时钟计时器使用Java语言和Swing界面库开发的小程序
时钟计时器使用Java语言和Swing界面库开发的小程序时钟计时器是一款使用Java语言和Swing界面库开发的小程序,它可以以时、分、秒的形式显示当前时间,并可以进行计时功能。
本文将介绍该小程序的开发过程,并分享一些有关Java语言和Swing界面库的知识。
一、程序开发环境搭建要使用Java语言和Swing界面库进行开发,首先需要安装Java开发工具包(JDK)和集成开发环境(IDE)。
在安装完成后,创建一个新的Java项目,并导入Swing库。
二、界面设计首先,我们需要设计一个界面来展示时钟和计时功能。
可以使用Swing库提供的组件来创建窗体、标签、按钮等。
1. 窗体设计在主类中创建一个窗体对象,设置标题、尺寸和布局等属性。
并将时钟和计时功能的组件添加到窗体中。
```javaJFrame frame = new JFrame("时钟计时器");frame.setSize(400, 300);frame.setLayout(new BorderLayout());```2. 时钟设计使用标签组件来显示当前时间。
可以使用Java提供的日期和时间类(如Date和Calendar)来获取当前时间,并将其格式化后设置为标签的文本。
```javaJLabel clockLabel = new JLabel();frame.add(clockLabel, BorderLayout.CENTER);// 获取当前时间Date now = new Date();SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");String time = sdf.format(now);// 设置标签文本clockLabel.setText(time);```3. 计时功能设计为计时功能设计按钮组件,并添加监听事件。
在按钮的监听器中,通过定时器类(如Timer)来实现每秒更新计时器的功能。
Java实现的简单数字时钟功能示例
Java实现的简单数字时钟功能⽰例本⽂实例讲述了Java实现的简单数字时钟功能。
分享给⼤家供⼤家参考,具体如下:应⽤名称:Java数字时钟⽤到的知识:Java GUI编程,线程开发环境:win8+eclipse+jdk1.8功能说明:可以显⽰当前系统的年⽉⽇、星期以及准确时间,并实时更新显⽰。
效果图:源代码:import javax.swing.JFrame;import javax.swing.JPanel;import java.awt.BorderLayout;import javax.swing.JLabel;import java.awt.Font;import java.text.SimpleDateFormat;import java.util.Date;public class Time extends JFrame implements Runnable{/****/private static final long serialVersionUID = 1L;private JLabel date;private JLabel time;public Time() {//初始化图形界⾯this.setVisible(true);this.setTitle("数字时钟");this.setSize(282, 176);this.setLocation(200, 200);this.setResizable(true);JPanel panel = new JPanel();getContentPane().add(panel, BorderLayout.CENTER);panel.setLayout(null);//时间time = new JLabel();time.setBounds(31, 54, 196, 59);time.setFont(new Font("Arial", Font.PLAIN, 50));panel.add(time);//⽇期date = new JLabel();date.setFont(new Font("微软雅⿊", Font.PLAIN, 13));date.setBounds(47, 10, 180, 22);panel.add(date);}//⽤⼀个线程来更新时间public void run() {while(true){try{date.setText(new SimpleDateFormat("yyyy 年 MM ⽉ dd ⽇ EEEE").format(new Date()));time.setText(new SimpleDateFormat("HH:mm:ss").format(new Date()));}catch(Throwable t){t.printStackTrace();}}}public static void main(String[] args) {new Thread(new Time()).start();}}PS:这⾥再为⼤家推荐⼏款时间及⽇期相关⼯具供⼤家参考使⽤:更多关于java相关内容感兴趣的读者可查看本站专题:《》、《》、《》和《》希望本⽂所述对⼤家java程序设计有所帮助。
JAVA课程设计钟表(含代码)
Java程序课程设计任务书钟表的设计与开发1、主要内容:创建一个钟表。
借助swing类和接口内部类的实现,在本程序中以实现Runnable接口内部类的形式创建多线程对象。
Runnable接口只定义了一个run()方法,所以调用start和sleep()方法时,必须创建Thread实例化对象。
Interrupt()方法的作用是中断线程。
其作用方式是:多线程对象.interrupt()。
2、具体要求(包括技术要求等):系统的功能要求:1.可以记录时间的钟表。
2.熟悉JAVA中swing的组件运用,基本工具的熟练掌握。
学习并掌握以下技术:Java等。
熟练使用以下开发工具:JCreator + JDK 1.6.0_02 等实现系统上述的功能。
3、进度安排:12月28日~ 12月29日:课程设计选题,查找参考资料12月29日~ 1月2日:完成程序代码的编写1月2日~ 1月3日:系统测试与完善1月4日~ 1月5日:完成课程设计报告,准备答辩4、主要参考文献[1]张帆.Java范例开发大全[M].北京:清华大学出版社,2010:0-831.[2]耿祥义,张跃平.Java大学实用教程[M].北京电子工业出版社,2008:213-216摘要随着经济全球化的发展,推动生活节奏的加快,也给时间赋予了更重要的意义。
基于方便人们更好的掌握时间,我们小组设计出了这个小时钟。
本时钟是一个基于Java语言设计而成的一个小程序,目的是显示时间,并且能调准时钟。
整个程序从符合操作简便、界面友好、灵活使用的要求出发,完成调用、调整的全过程。
本课程设计报告介绍了时钟的构成,论述了目标功能模块;给出了时钟设计的步骤,程序主要所用到的Swing组件以及graphics方法。
关键词:时钟,目录摘要 (II)目录 ......................................................................................................................................................... I II 第1章引言 .. (1)1.1课程设计内容 (1)1.2任务分工 (1)第2章时钟的设计 (2)2.1时钟功能的概述 (2)2.1.1时钟数字显示 (2)2.1.2时钟指针显示 (2)2.1.2时钟的设置 (2)第3章时钟的具体实现 (3)3.1界面设计 (3)3.1.1程序流程图 (3)3.1.1显示数字时钟效果 (3)3.1.2显示指针时钟完全效果图 (4)3.1.3设置窗口效果图 (6)第4章结束语 (8)致谢 (8)附录源代码 (9)第1章引言1.1课程设计内容本时钟编写时用到了Java中的Swing组件以及graphics方法,并具有下列处理功能(1)显示时钟功能显示钟表时间和数字时间(2)状态的可切换通过调整框图的大小,可以在数字时钟和指针时钟之间进行切换。
漂亮时钟java完整代码
漂亮时钟java完整代码这个时钟是用java写的,我觉得很完美,其中加载了声音和背景图片,我会把图片贴在这里,至于背景音乐可以根据自己的需要改动,程序运行后效果如下:今天把这个程序贴在这里,希望能帮到学习java的学弟学妹们。
源代码如下:import java.applet.Applet;import java.applet.AppletContext;import java.applet.AudioClip;import java.awt.*;import java.awt.event.*;import java.io.PrintStream;import java.util.Date;public class Clock extends Applet implements Runnable{Thread th1 = null;Image offScreenImage = null;Graphics offScreen = null;Image picture = null;int icount = 0;AudioClip song;private String n="look! My clock!";private String m="made by:";private String p="jessie with the number 200501109";public Clock(){}public void init(){try{offScreenImage = createImage(800, 600);offScreen = offScreenImage.getGraphics();}catch(Exception _ex){offScreen = null;}picture = getImage(getCodeBase(), "Clockscreen.jpg"); song=getAudioClip(getCodeBase(),"song.wav");song.loop();//加载声音}public void start(){th1 = new Thread(this);th1.start();}public void stop(){th1 = null ;}public static int vectorX(int i, int h, int j){int k = (i + h) % 360;int l = (int)((double)j* Math.cos((double)k * 2 * Math.PI / 360));return l;}public static int vectorY(int i, int h, int j){int k = (i + h) % 360;int l = (int)((double)j* Math.sin((double)k * 2 * Math.PI / 360)); return l;}public void run(){Thread.currentThread().setPriority(5);do{try{Thread.sleep(1000);}catch(InterruptedException _ex) { }repaint();}while(true);}public void paint(Graphics g) //防止闪屏{update(g);}public synchronized void update(Graphics g){if(offScreen != null){paintApplet(offScreen);g.drawImage(offScreenImage, 0, 0, this);return;}else{paintApplet(g);return;}}public void paintApplet(Graphics g)//具体画页面 {g.fillRect(0, 0, 677, 555);g.drawImage(picture, 0, 0, this);g.setColor(Color.pink); //设置字体颜色g.setFont(new Font("Arial",Font.PLAIN,24)); //设置文本字体和大小 g.drawString(n,20,50); //写文本“look!My clock!”g.drawString(m,200,510); //写文本"made by:"g.drawString(p,300,550);//写文本"jessie with the number 200501109"g.setColor(Color.pink);//画表盘g.drawOval(425,58,200,200);g.drawOval(415,48,220,220);for(int x=0;x<360;x+=6){if(x%5!=0){int u1=vectorX(x,270,100);int v1=vectorY(x,270,100);int u2=vectorX(x,270,110);int v2=vectorY(x,270,110);g.setColor(Color.pink);g.drawLine(525+u1,158+v1,525+u2,158+v2);}else{int u3=vectorX(x,270,90);int v3=vectorY(x,270,90);int u4=vectorX(x,270,110);int v4=vectorY(x,270,110);g.setColor(Color.pink);g.drawLine(525+u3,158+v3,525+u4,158+v4);}};String s1="12";String s2="3";String s3="6";String s4="9";g.setColor(Color.pink);g.drawString(s1,505,50);g.drawString(s2,635,165);g.drawString(s3,520,285);g.drawString(s4,400,165);g.fillOval(522,155,6,6);//表盘中心的圆点和圆圈g.setColor(Color.yellow);g.drawOval(518,149,14,14);Date date = new Date();int i = date.getMinutes();int j = i * 6;int kk = (date.getHours() ) % 24;g.setFont(new Font("Helvetica", 1, 28));//设置字体,显示数码时间;String s = new String();s = kk+ ":" + date.toString().substring(14, 19);g.setColor(Color.pink);g.drawString(s,465, 320);int k= (date.getHours() ) % 12;//开始获取时间经过计算画出时针、分针、秒针 int l = k * 30 + (i / 12) * 6;int a = vectorX(l,255,63);int b= vectorY(l,255,63);int c = vectorX(l,270,63);int d= vectorY(l,270,63);int x1[]={525,525+a/4,525+c};int y1[]={158,158+b/4,158+d};g.setColor(Color.pink);g.fillPolygon(x1,y1,3);int a1 = vectorX(j,255,73);int b1= vectorY(j,255,73);int c1= vectorX(j,270,73);int d1= vectorY(j,270,73);int x2[]={525,525+a1/4,525+c1};int y2[]={158,158+b1/4,158+d1};g.setColor(Color.pink);g.fillPolygon(x2,y2,3);int k1 = date.getSeconds() * 6;int a2 = vectorX(k1,255,85);int b2= vectorY(k1,255,85);int c2 = vectorX(k1,270,85);int d2= vectorY(k1,270,85);int x3[]={525,525+a2/4,525+c2};int y3[]={158,158+b2/4,158+d2};g.setColor(Color.pink);g.fillPolygon(x3,y3,3);}}然后还有html文件,内容如下:<HTML><BODY><APPLET CODE="Clock.class"HEIGHT=597 WIDTH=773></APPLET> </BODY></HTML>其中的图片如下。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
package com.lw;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class DigitalClock extends JFrame {
/**
*
*/
private static final long serialV ersionUID = 4962111797317773666L;
private JPanel contentPane;
private JLabel label;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DigitalClock frame = new DigitalClock();
frame.setV isible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public DigitalClock() {
addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) {
do_this_windowActivated(e);
}
});
setTitle("\u6570\u5B57\u65F6\u949F");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 200, 100);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
label = new JLabel("New label");
label.setFont(new Font("微软雅黑", Font.BOLD, 20));
label.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(label, BorderLayout.CENTER);
}
private String format(int number) {
return number < 10 ? "0" + number : "" + number;// 如果数字小于10就在其前面加0补齐
}
private String getTime() {
Calendar calendar = new GregorianCalendar();
int hour = calendar.get(Calendar.HOUR_OF_DAY); // 获得当前小时
int minute = calendar.get(Calendar.MINUTE); // 获得当前分钟
int second = calendar.get(Calendar.SECOND); // 获得当前秒
return format(hour) + ":" + format(minute) + ":" + format(second);// 返回格式化的字符串
}
protected void do_this_windowActivated(WindowEvent e) {
new Thread() {
public void run() {
while (true) {// 让时钟一直处于更新状态
label.setText(getTime()); // 更新时钟
try {
Thread.sleep(1000); // 休眠一秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}.start();
}
}。