java简易电子时钟代码
JAVA计时器(秒表)程序代码

Java计时器(秒表)功能:能实现计时,暂停,清零,记录功能。
如下图:程序运行状态:源代码:import javax.swing.*;import java.awt.*;import .*;public class Test {public static void main(String[] args){new window("计时器");}}class window extends JFrame{int ON=0,i=0,j=0,k=0,count=0,num=1,R=0;JButton button1,button2,button3,button4,button5; JTextField file1,file2,file3;JTextArea file;FlowLayout flow;String a,b,c;window(String name){file1=new JTextField(2);file2=new JTextField(2);file3=new JTextField(2);file1.setEditable(false);file2.setEditable(false);file3.setEditable(false);file=new JTextArea(10,8);file.setEditable(false);button1=new JButton("开始");button2=new JButton("暂停");button3=new JButton("清零");button4=new JButton("记录");button5=new JButton("清空记录");flow=new FlowLayout();flow.setAlignment(FlowLayout.LEFT); flow.setHgap(20);flow.setVgap(10);setTitle(name);setSize(210,400);setLayout(flow);add(file1);add(new JLabel(":"));add(file2);add(new JLabel(":"));add(file3);add(button1);add(button2);add(button3);add(button4);add(button5);add(file);setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); file1.setText("0");file2.setText("0");file3.setText("0");validate();button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ON=1; //开始,暂停控制开关}}); //开始按钮button2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ ON=0;}}); //暂停按钮button3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ R=1; //清零控制开关}}); //清零按钮button4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){count=1; //记录控制开关a=String.valueOf(i);b=String.valueOf(j);c=String.valueOf(k);}}); //记录按钮button5.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){file.setText("");num=1;}}); //清除记录按钮while(true){validate();if(ON==1) //开始或暂停判断{file1.setText(String.valueOf(i));file2.setText(String.valueOf(j));file3.setText(String.valueOf(k));if(k==99){k=-1;j++;}if(j==60){k=0;j=0;i++;}if(i==24){i=0;j=0;k=0;}try{Thread.sleep(10);}catch(Exception e){}k++;}if(count==1)//记录判断{file.append(String.valueOf(num));file.append(". ");file.append(a);file.append(":");file.append(b);file.append(":");file.append(c);file.append("\n");num++;count=0;}if(R==1)//清零判断{i=j=k=0;file1.setText(String.valueOf(i));file2.setText(String.valueOf(j));file3.setText(String.valueOf(k));R=0;}}}}。
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数字时钟源程序代码

import java.awt.*;import java.util.*;import javax.swing.*;//数字时钟public class ClockDemo extends JFrame implements Runnable{Thread clock;public ClockDemo(){super("数字时钟"); //调用父类构造函数setFont(new Font("Times New Roman",Font.BOLD,60)); //设置时钟的显示字体start(); //开始进程setSize(280,100); //设置窗口尺寸setVisible(true); //窗口可视this.setLocation(440,330);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序}public void start(){ //开始进程if (clock==null){ //如果进程为空值clock=new Thread(this); //实例化进程clock.start(); //开始进程}}public void run(){ //运行进程while (clock!=null){repaint(); //调用paint方法重绘界面try{Thread.sleep(1000); //线程暂停一秒(1000毫秒)}catch (InterruptedException ex){ex.printStackTrace(); //输出出错信息}}}public void stop(){ //停止进程clock=null;}public void paint(Graphics g){ //重载组件的paint方法Graphics2D g2=(Graphics2D)g; //得到Graphics2D对象Calendar now=new GregorianCalendar(); //实例化日历对象String timeInfo=""; //输出信息int hour=now.get(Calendar.HOUR_OF_DAY); //得到小时数int minute=now.get(Calendar.MINUTE); //得到分数int second=now.get(Calendar.SECOND); //得到秒数if (hour<=9)timeInfo+="0"+hour+":"; //格式化输出elsetimeInfo+=hour+":";if (minute<=9)timeInfo+="0"+minute+":";elsetimeInfo+=minute+":";if (second<=9)timeInfo+="0"+second;elsetimeInfo+=second;g.setColor(Color.orange); //设置当前颜色为白色Dimension dim=getSize(); //得到窗口尺寸g.fillRect(0,0,dim.width,dim.height); //填充背景色为白色g.setColor(Color.black); //设置当前颜色为橙色g.drawString(timeInfo,20,80); //显示时间字符串}public static void main(String[] args){new ClockDemo();}}。
JAVA时钟代码

import javax.swing.*; //时钟import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import java.awt.*;import java.util.Calendar;import java.util.GregorianCalendar;class Clock extends JFrame implements ActionListener{ int x,y,x0,y0,r,h,olds_x,olds_y,oldm_x,oldm_y,oldh_x,oldh_y,ss,mm,hh,old_m,old_h,ang;final double RAD=Math.PI/180; //度数转换成弧度的比例//构造函数创建了一个窗体public Clock(){ super("时钟"); //设置标题setSize(250,250); //设置窗口尺寸setBackground(Color.WHITE); //设置背景颜色setLocation(300,150); //设置窗口位置坐标setResizable(false); //使窗口可以最小化和关闭,但是不能任意改变大小setVisible(true); //设置组建可见int delay = 100; //设置延时//创建一个监听事件ActionListener drawClock = new ActionListener(){ public void actionPerformed(ActionEvent evt) { repaint(); } };new Timer(delay,drawClock).start(); //创建时间计数器,每秒触发一次}public void actionPerformed(ActionEvent e){//实现ActionListener接口必须实现的方法}//绘制图形public void paint(Graphics g){Graphics2D g2D = (Graphics2D)g;Insets insets = getInsets();int L = insets.left/2,T = insets.top/2;h = getSize().height;g.setColor(Color.black);//画圆g2D.setStroke(new BasicStroke(4.0f));g.drawOval(L+40,T+40,h-80,h-80);r=h/2-40;x0=40+r-5+L;y0=40+r-5-T;ang=60;//绘制时钟上的12个数字for(int i=1;i<=12;i++){x=(int)((r-9)*Math.cos(RAD*ang)+x0);y=(int)((r-9)*Math.sin(RAD*ang)+y0);g.drawString(""+i,x,h-y);ang-=30;}//获得当前系统时间Calendar now= new GregorianCalendar();int nowh= now.get(Calendar.HOUR_OF_DAY); int nowm= now.get(Calendar.MINUTE);int nows= now.get(Calendar.SECOND);String st;if(nowh<10) st="0"+nowh;else st=""+nowh;if(nowm<10) st+=":0"+nowm;else st+=":"+nowm; if(nows<10) st+=":0"+nows;else st+=":"+nows;//在窗体上显示时间g.setColor(Color.white);//g.fillRect(L,T,50,28);//g.setColor(Color.black);//g.drawString(st,L+2,T+26);////计算时间与度数的关系ss=90-nows*6;mm=90-nowm*6;hh=90-nowh*30-nowm/2;x0=r+40+L;y0=r+40+T;g2D.setStroke(new BasicStroke(1.0f));//秒针粗细//擦除秒针if(olds_x>0){g.setColor(getBackground());g.drawLine(x0,y0,olds_x,h-olds_y);}Else{old_m = mm;old_h = hh;}//绘制秒针x=(int)(r*0.9*Math.cos(RAD*ss))+x0;//长度y=(int)(r*0.9*Math.sin(RAD*ss))+y0-2*T;g.setColor(Color.black);//指针颜色g.drawLine(x0,y0,x,h-y);//轨迹olds_x=x;olds_y=y;g2D.setStroke(new BasicStroke(2.2f));//分针粗细//擦除分针if(old_m!=mm){g.setColor(getBackground());g.drawLine(x0,y0,oldm_x,h-oldm_y);}//绘制分针x=(int)(r*0.7*Math.cos(RAD*mm))+x0;//长度y=(int)(r*0.7*Math.sin(RAD*mm))+y0-2*T;g.setColor(Color.red);//颜色g.drawLine(x0,y0,x,h-y);oldm_x=x;oldm_y=y;old_m=mm;g2D.setStroke(new BasicStroke(3.4f));//时针粗细//擦除时针if(old_h!=hh){g.setColor(getBackground());g.drawLine(x0,y0,oldh_x,h-oldh_y);}//绘制时针x=(int)(r*0.5*Math.cos(RAD*hh))+x0;//长度y=(int)(r*0.5*Math.sin(RAD*hh))+y0-2*T;g.setColor(Color.red);//颜色g.drawLine(x0,y0,x,h-y);oldh_x=x;oldh_y=y;old_h=hh;}public static void main(String[] args){ Clock c = new Clock(); } }3Dimport java.applet.Applet;import java.awt.BorderLayout;import com.sun.j3d.utils.applet.MainFrame;import com.sun.j3d.utils.geometry.*;import com.sun.j3d.utils.universe.*;import javax.media.j3d.*;import javax.vecmath.*;import com.sun.j3d.utils.behaviors.mouse.MouseRotate;import com.sun.j3d.utils.behaviors.mouse.MouseZoom;import com.sun.j3d.utils.behaviors.mouse.MouseTranslate;public class AWTFrameJ3D{ private static final long serialVersionUID = 1L;Canvas3D cv = null;public static void main(String s[]){ AWTFrameJ3D hd = new AWTFrameJ3D();hd.constractJava3D();}/*构造方法创建Frame和Canvas3D画布对象,并将Canvas3D嵌入到Frame中*/public AWTFrameJ3D(){GraphicsConfigTemplate3D template = new GraphicsConfigTemplate3D();GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();GraphicsDevice device = env.getDefaultScreenDevice();GraphicsConfiguration config = device.getBestConfiguration(template);// 新建Canvas3D对象,Canvas3D对象是一个用于显示虚拟世界场景的绘制结果的画布cv = new Canvas3D(config);// 新建Frame对象Frame dframe = new Frame(config);dframe.setTitle("模型读取中");dframe.setLayout(new BorderLayout());// 将Canvas3D对象嵌入到Frame对象中dframe.add(cv, BorderLayout.CENTER);dframe.setSize(500, 400);// 添加窗口监听器实现关闭窗口(Frame),关闭窗口时退出程序dframe.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent ev){ System.out.print("退出程序!");System.exit(0);} }};// 使用Toolkit更改Java应用程序标题栏默认图标Toolkit tk = Toolkit.getDefaultToolkit();Image image = tk.createImage("images/earth.jpg"); /* image.gif是你的图标 */ dframe.setIconImage(image);// 使用Toolkit把默认的鼠标图标改成指定的图标:// Toolkit tk=Toolkit.getDefaultToolkit();Image img = tk.getImage("images/earth.jpg"); /* mouse.gif是你的图标 */Cursor cu = tk.createCustomCursor(img, new Point(10, 10), "stick");dframe.setCursor(cu);// 现将Frame窗口可视化之后,再绘制3D场景内容dframe.setVisible(true);}/**构建3D虚拟世界场景*/public void constractJava3D(){ // 创建场景图分支BranchGroup bg = createSceneGraph();pile();// 将观察分支关联到一个Canvas3D对象,以显示视图的绘制结果SimpleUniverse su = new SimpleUniverse(cv);su.getViewingPlatform().setNominalViewingTransform();// 把场景图关联到SimpleUniverse对象之后,整个场景就开始绘制了su.addBranchGraph(bg);// 现绘制3D场景内容,再将Frame窗口可视化// dframe.setVisible(true);}/**创建3D场景内容*/private BranchGroup createSceneGraph(){ // 创建BranchGroup对象作为根节点BranchGroup root = new BranchGroup();// objectAppearance ap = new Appearance();ap.setMaterial(new Material());Font3D font = new Font3D(new Font("SansSerif", Font.PLAIN, 1),new FontExtrusion());Text3D text = new Text3D(font, "Hello 3D");Shape3D shape = new Shape3D(text, ap);// transformationTransform3D tr = new Transform3D();tr.setScale(0.5);tr.setTranslation(new Vector3f(-0.95f, -0.2f, 0f));TransformGroup tg = new TransformGroup(tr);root.addChild(tg);tg.addChild(shape);// lightPointLight light = new PointLight(new Color3f(Color.white), new Point3f(1f, 1f, 1f), new Point3f(1f, 0.1f, 0f));BoundingSphere bounds = new BoundingSphere();light.setInfluencingBounds(bounds);root.addChild(light);return root;}}。
Java模拟时钟制作案例

美化指针
调用AffineTransform
public AffineTransform sc =new AffineTransform(); sc.setToRotation(Math.PI/30f*(s1-15),125,125); g2.fill(tick_s.createTransformedShape(sc));
程序代码
主类
程序代码
程序代码
运行效果
运行效果
面板刻度
绘制刻度
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; }
运行效果程序代码程序代码程序代码程序代码程序代码代码优化与改进以上的代码已经能基本完成时钟的功能
Java模拟时钟制 作案例
Java开发实例
需求分析
模拟时钟,把它放在程序中可以给人一种清 新的感觉。比起数字时钟来说,有一定的真 实感怀旧情结。看到秒针一下一下的转动, 时时提醒,时间在不断流逝,要我们珍惜时 间。 子在川上曰:逝者如斯夫。
坐标的转换,使用方法
调用方法:
p0=xy(125,125,75,s1*6); s.x1=p0.getX(); s.y1=p0.getY(); p0=xy(125,125,65,m1*6); m.x1=p0.getX(); m.y1=p0.getY(); p0=xy(125,125,55,(h1*30+m1/2f)); h.x1=p0.getX(); h.y1=p0.getX();
数字时钟代码

数字时钟代码1. 介绍数字时钟是一种常见的显示时间的装置,它通过数字显示屏显示当前的小时和分钟。
本文档将介绍如何编写一个简单的数字时钟代码。
2. 代码实现以下是一个基本的数字时钟代码实现示例:import timewhile True:current_time = time.localtime()hour = str(current_time.tm_hour).zfill(2)minute = str(current_time.tm_min).zfill(2)second = str(current_time.tm_sec).zfill(2)clock_display = f"{hour}:{minute}:{second}"print(clock_display, end="\r")time.sleep(1)代码说明:- `time.localtime()` 函数返回当前时间的结构化对象,包括小时、分钟和秒等信息。
- `str(current_time.tm_hour).zfill(2)` 将小时转换为字符串,并使用 `zfill()` 方法填充到两位数。
- `str(current_time.tm_min).zfill(2)` 和`str(current_time.tm_sec).zfill(2)` 同理处理分钟和秒。
- 使用 f-string 格式化字符串 `clock_display`,将小时、分钟和秒显示为 `` 的形式。
- `print(clock_display, end="\r")` 使用 `\r` 实现覆盖打印,使得时钟在同一行连续显示。
- `time.sleep(1)` 让程序每隔一秒更新一次时间。
请注意,上述代码需要在支持 Python 的环境中运行。
3. 结束语通过以上的代码实现,我们可以编写一个简单的数字时钟。
JAVA可视化闹钟源码

JAVA可视化闹钟源码概述⼀些同学的Java课设有这样⼀个问题,⽐较感兴趣就做了⼀下功能介绍:1、可增加闹钟2、可删除闹钟3、时间到了响铃4、关闭闹钟不会丢失闹钟(因为闹钟存储在txt⽂件中,不会因程序关闭就终⽌)缺点1、没有使⽤多线程,闹钟响起时只能等待1分钟或者关闭程序2、界⾯设计不够美观,后期有时间会进⾏修改,重新设计3、没有闹钟修改的功能,虽然可以通过增删来达到修改的⽬的,但功能仍然属于空缺范围1package Clock;23import sun.audio.AudioPlayer;4import sun.audio.AudioStream;56import javax.swing.*; //awt和swing是做界⾯⽤的类7import java.awt.*;8import java.awt.event.ActionEvent;9import java.awt.event.ActionListener;10import java.awt.event.WindowAdapter;11import java.awt.event.WindowEvent;12import java.io.*; //io流⽤于读写⽂件,包括增删闹钟、打开铃声等等13import java.util.Calendar; //⽤于获取当前时间的类14import java.util.GregorianCalendar;//标准阳历15import java.util.StringTokenizer; //读取⽂件转换成计算机语⾔⽤的类16/*171 计时器18要求1:⼀个带有可视化界⾯的钟表。
19要求2:可以添加若⼲个闹钟。
20要求3:具备持久化功能,关闭程序不能丢失闹钟。
21要求4:闹钟是可编辑,可删除的。
2223实现:先创建⼀个⾯板显⽰闹钟,⾯板内创建按钮增加闹钟,按钮查看闹钟,按钮删除闹钟24线程间隔1s读取时间和闹钟⽐较2526*/27public class ClockTry extends JFrame implements Runnable {28/* 成员变量 */29private JPanel xx; //总的⾯板30private JComboBox ho; //hour选择时间的下拉框31private JComboBox mi; //min选择分钟的下拉框32private JButton tjnz; //添加闹钟的按钮33private JButton schour; //删除闹钟的按钮34private String filename = "D://homework//java//Gui//src//Clock//0.wav"; //所有的路径改这两个地⽅就可以了35private String pathname = "D://homework//java//Gui//src//Clock//nz.txt"; // 绝对路径或相对路径都可以,写⼊⽂件时演⽰相对路径,读取以上路径的input.txt⽂件3637private int HOUR; //定义HOUR⽤于接收按钮按下从下拉框中获取的数据38private int MIN; //同上3940int x = 100, y = 100, r = 100; // (x,y)为(0,0)点,表⽰原点41int h, m, s; // 时,分,秒42double rad = Math.PI / 180; // 1°4344private String[][] str= new String[100][2]; //定义⼆维数组,⽤于存储以及对⼩时和分针的操作,暂定为100个闹钟于是定义为【100】【2】45/**46 *读取⽂件,每次的增删都需要对数据进⾏读取,将数据写在⾯板上也需要读取数据47*/48public void readFile() {49try (FileReader reader = new FileReader(pathname); //创建⼀个FilReader对象,将⽂件读出来,相当于请教⼀个当地⼈,当地⼈了解本地⽂化,但是语⾔不通听不懂50 BufferedReader br = new BufferedReader(reader) // 建⽴⼀个对象,它把⽂件内容转成计算机能读懂的语⾔,相当于请⼀个翻译,把当地⼈读取的东西转换成计算机能懂的东西51 ) {52 String line;5354int i =0;55while ((line = br.readLine()) != null) { //翻译理解的东西存到line⾥⾯56int j =0;57 StringTokenizer st = new StringTokenizer(line, ":"); //重点:由于存储数据时都是时间,道理来说都是数字,⽆法区分⼩时部分和分钟部分58while (st.hasMoreTokens()){ //每读取⼀次读到的内容 //所以这⾥⽤分割符“:”来分割,相应的,后⾯的写⼊⽂件也应该已“:”分割进⾏写⼊59 str[i][j]=st.nextToken(); //把读到的内容存储在数组⾥⾯便于后⾯的操做——增删60 j++; //包括上⾯的j=0,是将for循环拆分放进while循环中,要不然循环写起来也很⿇烦61 }62//System.out.print(str[i][0]+":"+str[i][1]); 写的时候⽤来在控制台打印查看效果63//System.out.println();64 i++;65 j = 0;66 }67 } catch (IOException e) {68 e.printStackTrace(); //try……catch抛出异常69 }70 }717273/**74 * 写⼊TXT⽂件75*/76public void writeFile() {77 HOUR = Integer.valueOf(ho.getSelectedIndex()); //获取下拉框中的值,存储到HOUR中78 MIN = Integer.valueOf(mi.getSelectedIndex());79 String x = HOUR + ":" + MIN;80try (FileWriter writer = new FileWriter(pathname,true); //同上⾯的读取,本地⼈写⼊,注意:后⾯的append:true是表⽰不是重新写,⽽是在后⾯追加81 BufferedWriter out = new BufferedWriter(writer) //翻译⼀下再写⼊82 ) {8384 out.write(HOUR + ":" + MIN + "\r\n"); //这⾥写⼊的时候把:写进去了!85 out.flush(); // 把缓存区内容压⼊⽂件,计算机的存储过程,存在缓存区再写⼊⽂件86 JOptionPane.showMessageDialog(null,"闹钟添加成功!","添加闹钟提醒",RMATION_MESSAGE); //提⽰框:添加闹钟成功87 } catch (IOException e) {88 e.printStackTrace();8990 }9192 }939495/**96 * 删除闹钟,实际上是先将要删除的数据找到移除数组,再将数组重新写⼊,所以要先读取⽂件,再重新写⼊97*/98public void shanchuFile() {99 HOUR = Integer.valueOf(ho.getSelectedIndex());100 MIN = Integer.valueOf(mi.getSelectedIndex());101try (FileWriter writer = new FileWriter(pathname); //没有append:true,表⽰重新写!102 BufferedWriter out = new BufferedWriter(writer)103 ) {104 readFile();105for (int i = 0; i < 100; i++) {106if (Integer.valueOf(str[i][0])==HOUR && Integer.valueOf(str[i][1])==MIN){107continue;108 }109else{110 out.write(str[i][0]+":"+str[i][1]+"\r\n"); // \r\n即为换⾏111 }112 }113114//out.write("1"+"1"+"\r\n"); // \r\n即为换⾏115 out.flush(); // 把缓存区内容压⼊⽂件116 } catch (IOException e) {117 e.printStackTrace();118 }catch (NumberFormatException e){119 System.out.println("this isn't exist!");120 JOptionPane.showMessageDialog(null,"该闹钟已删除!","删除闹钟提醒",RMATION_MESSAGE); //弹窗提⽰121 }122 }123124/* 初始化函数 */125public void init() {126127 Calendar now = new GregorianCalendar(); //获取当前时间128/*129 * GregorianCalendar(标准阳历)130 * 是Calendar(⽇历)【国际环境下都能运⾏的程序】131 * 的⼦类132*/133 s = now.get(Calendar.SECOND) * 6; // 秒针转换成⾓度:1秒,秒针动⼀次,转动6°134 m = now.get(Calendar.MINUTE) * 6; // 分针转换为⾓度:1分,分针动⼀次,转动6°135 h = now.get(Calendar.HOUR) * 30 + now.get(Calendar.MINUTE) / 12 * 6; // 先把分化为⼩时,再乘以6°,因为分针转12°,时针才会转1°,⼀⼩时中间有5格,数学问题136/*137 * Calendar.HOUR 显⽰范围:1-12(⽆论AM还是PM) Calendar.HOUR_OF_DAY 显⽰范围:1-24(包括PM138*/139140 Thread t = new Thread(this); //添加线程,线程⽬标是整个程序,this141 t.start(); //线程就绪142 }143144public void paint(Graphics g) { //awt中的⽅法,因为要时时显⽰闹钟,所以不得不使⽤绘画的⽅式,不断重绘145super.paint(g);146/*147 * paint(g)函数会重绘图像,要加上super.paint(g),表⽰在原来图像的基础上,再画图。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
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 = new
SimpleDateFormat("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();
}
}
运行结果:。