导航:首页 > 编程语言 > java计时

java计时

发布时间:2022-02-06 21:28:55

java需要一条秒表计时器代码

好吧,已看到你的评论,我在这里再回答一次:

1)你所说的置顶如果是属于悬浮窗效果,那么JFrame实例化后,再添加一行如下的代码:

form1.setAlwaysOnTop(true);//总是允许窗口置顶

2)时分秒更简单了,除一除转转换就行了,没有技术含量。

3)快捷键通过JButton类的setMnemonic方法实现

So,综上,整个程序的实现算法如下:

packagehky.example;

importjava.awt.BorderLayout;
importjava.awt.Container;
importjava.awt.GridLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.awt.event.KeyEvent;
importjava.awt.event.WindowEvent;
importjava.awt.event.WindowListener;
importjava.io.*;
importjava.util.*;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JOptionPane;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
importjavax.swing.plaf.OptionPaneUI;


publicclassDemo{
staticbooleanisRuning=false;
staticbooleanisFirst=true;
staticIntegerhmsCounter=0;
staticinthour,minute,second;

@SuppressWarnings("unchecked")
publicstaticvoidmain(String[]args)throwsException{

JFrameform1=newJFrame("Form1");
form1.setAlwaysOnTop(true);//1)总是允许窗口置顶

JTextFieldjTextField=newJTextField(10);
jTextField.setSize(10,10);
jTextField.setText("0");
jTextField.setEditable(false);

JButtonjButton=newJButton("开始");
jButton.setSize(10,10);


Threadthread=newThread(newRunnable(){
@Override
publicvoidrun(){
while(true){
while(isRuning){
++hmsCounter;
//3)时分秒显示
hour=hmsCounter/3600;
minute=hmsCounter%3600/60;
second=hmsCounter%60;
jTextField.setText(hour+"时"+minute+"分"+second+"秒");
try{Thread.sleep(1000);}catch(Exceptione2){}
}
try{Thread.sleep(200);}catch(Exceptione2){}//修复上一次回答的版本可能会存在的Bug
}
}
});

jButton.setMnemonic(KeyEvent.VK_ENTER);//2)给JButton发送Alt+Enter快捷键
jButton.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
Stringtext=jButton.getText().equals("开始")?"暂停":"开始";
jButton.setText(text);
isRuning=!isRuning;
if(isFirst){
thread.start();
isFirst=false;
}
}
});

JPanelpanel=newJPanel();
panel.setSize(200,200);
panel.add(jTextField,BorderLayout.NORTH);
panel.add(jButton,BorderLayout.CENTER);
form1.add(panel);
form1.setBounds(200,100,250,150);
form1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
form1.addWindowListener(newWindowListener(){
@Override
publicvoidwindowOpened(WindowEvente){
//TODOAuto-generatedmethodstub

}

@Override
publicvoidwindowIconified(WindowEvente){
//TODOAuto-generatedmethodstub

}

@Override
publicvoidwindowDeiconified(WindowEvente){
//TODOAuto-generatedmethodstub

}

@Override
publicvoidwindowDeactivated(WindowEvente){
//TODOAuto-generatedmethodstub

}

@Override
publicvoidwindowClosing(WindowEvente){
//窗口关闭前取出文本框的数字保存到外部文件,代码在此处写
JOptionPane.showMessageDialog(null,"Areyousureclosing?");
}

@Override
publicvoidwindowClosed(WindowEvente){
//TODOAuto-generatedmethodstub

}

@Override
publicvoidwindowActivated(WindowEvente){
//TODOAuto-generatedmethodstub

}
});

form1.setVisible(true);
}
}

❷ JAVA计时器的JAVA代码

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Clock extends Applet {
private final Panel pnlTop = new Panel();
private final Panel pnlBot = new Panel();
private final Label lblDate = new Label();
private final Label lblTime = new Label();
private final Label lblWatch = new Label();
private final Button btnGo = new Button("开始");
private final Button btnReset = new Button("重置");
private final Label lblSplit = new Label();
private final Button btnSplit = new Button("定点");
private final Button btnSplitReset = new Button("定点重置");
private final Button btnLapAdd = new Button("冲线");
private final Button btnLapReset = new Button("冲线重置");
private final java.awt.List lstLaps = new java.awt.List();
private final UpdateClockThread ucThread = new UpdateClockThread();
private final StopwatchThread swThread = new StopwatchThread();

private class btnGoListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if ((btnGo.getLabel().equals("开始")) ||
(btnGo.getLabel().equals("继续"))) {
// Start the clock!
swThread.go();
btnGo.setLabel("停止");
btnGo.setBackground(Color.red);
} else if (btnGo.getLabel().equals("停止")) {
// Stop the clock!
swThread.noGo();
btnGo.setLabel("继续");
btnGo.setBackground(Color.green);
}
}
}

private class btnResetListener implements ActionListener {
/** Actually run when the button gets clicked.
*@param e The event
*/
public void actionPerformed(ActionEvent e) {
swThread.reset();
btnGo.setLabel("开始");
btnGo.setBackground(Color.green);
}
}

/** Listens to the Split button.
* @version CS2136 - Term D'00 - Assignment 5
* @author Peter Cooper Jr.
*/
private class btnSplitListener implements ActionListener {
/** Actually run when the button gets clicked.
*@param e The event
*/
public void actionPerformed(ActionEvent e) {
lblSplit.setText(lblWatch.getText());
}
}

/** Listens to the Split Reset button.
* @version CS2136 - Term D'00 - Assignment 5
* @author Peter Cooper Jr.
*/
private class btnSplitResetListener implements ActionListener {
/** Actually run when the button gets clicked.
*@param e The event
*/
public void actionPerformed(ActionEvent e) {
lblSplit.setText("");
}
}

/** Listens to the Lap Add button.
* @version CS2136 - Term D'00 - Assignment 5
* @author Peter Cooper Jr.
*/
private class btnLapAddListener implements ActionListener {
/** Actually run when the button gets clicked.
*@param e The event
*/
public void actionPerformed(ActionEvent e) {
swThread.addLap();
}
}

/** Listens to the Lap Reset button.
* @version CS2136 - Term D'00 - Assignment 5
* @author Peter Cooper Jr.
*/
private class btnLapResetListener implements ActionListener {
/** Actually run when the button gets clicked.
*@param e The event
*/
public void actionPerformed(ActionEvent e) {
swThread.resetLap();
}
}

/** A thread that updates the current date & time.
* @version CS2136 - Term D'00 - Assignment 5
* @author Peter Cooper Jr.
*/
private class UpdateClockThread extends Thread {
/** The actual work of the thread.
*/
public void run() {
while (true) {
Calendar now = Calendar.getInstance();
String month = Integer.toString(now.get(Calendar.MONTH)+1);
String date = Integer.toString(now.get(Calendar.DAY_OF_MONTH));
String year = Integer.toString(now.get(Calendar.YEAR));
String hour = Integer.toString(now.get(Calendar.HOUR));
if (hour.equals("0")) hour = "12";
String minute = Integer.toString(now.get(Calendar.MINUTE));
if (minute.length() == 1) minute = "0" + minute;
String second = Integer.toString(now.get(Calendar.SECOND));
if (second.length() == 1) second = "0" + second;
String ampm = now.get(Calendar.AM_PM) == Calendar.AM
? "AM" : "PM";

lblDate.setText(month + "/" + date + "/" + year);
lblTime.setText(hour + ":" + minute + ":" + second
+ " " + ampm);
try {
sleep(500);
} catch (InterruptedException e) {}
}
}
}

private class StopwatchThread extends Thread {
/** Whether or not stopwatch is running. */
private boolean going = false;
/** Stores elapsed milliseconds of previous runs. */
private long prevElapsed = 0;
/** Stores beginning time of this run. */
private Date startDate = new Date();
/** Current lap number. */
private int lapNum = 0;
/** Elapsed time at end of last lap. */
private long lastLapTime = 0;

/** Returns elapsed time in milliseconds.
*@return The elapsed time
*/
private long elapsedTime() {
return prevElapsed +
(going ? new Date().getTime() - startDate.getTime() : 0);
}
/** Changes the number of elapsed milliseconds into a string.
*@param time Number of elapsed milliseconds
*@return The elapsed time as a string.
*/
private String msToString(long time) {
String ms, sec, min;
if (time % 10 >= 5) //round to nearest hundredth
time += 5;
ms = Long.toString(time % 1000);
while (ms.length() < 3)
ms = "0" + ms;
ms = ms.substring(0, ms.length() - 1);
time /= 1000;
sec = Long.toString(time % 60);
if (sec.length() == 1) sec = "0" + sec;
time /= 60;
min = Long.toString(time);
return min + ":" + sec + "." + ms;
}

public void go() {
startDate = new Date();
going = true;
}
public void noGo() {
prevElapsed = elapsedTime();
going = false;
}
public void reset() {
going = false;
prevElapsed = 0;
lastLapTime = 0;
}
public void addLap() {
long elapsed = elapsedTime();
lstLaps.add("冲线 " + Integer.toString(++lapNum)+ " -- " +
"用时: " + msToString(elapsed) + " -- " +
"冲线时间: " + msToString(elapsed - lastLapTime));
lastLapTime = elapsed;
}
/** Resets the lap list.
*/
public void resetLap() {
lstLaps.removeAll();
lapNum = 0;
lastLapTime = 0;
}
/** Main code of the thread.
*/
public void run() {
while (true) {
lblWatch.setText(msToString(elapsedTime()));
yield();
}
}
}

public void init() {
setLayout(new GridLayout(2,1));
setBackground(Color.lightGray);
setForeground(Color.black);
pnlTop.setLayout(new GridLayout(4,4));
pnlTop.add(new Label("日期:"));
pnlTop.add(lblDate);
pnlTop.add(new Label("时间:"));
pnlTop.add(lblTime);
pnlTop.add(new Label("计时:"));
//lblWatch.setBackground(Color.black);
lblWatch.setForeground(Color.blue);
pnlTop.add(lblWatch);
pnlTop.add(btnGo);
btnGo.setBackground(Color.green);
pnlTop.add(btnReset);
pnlTop.add(new Label("定点:"));
pnlTop.add(lblSplit);
pnlTop.add(btnSplit);
pnlTop.add(btnSplitReset);
pnlTop.add(new Label("冲线时间:"));
pnlTop.add(new Label());
pnlTop.add(btnLapAdd);
pnlTop.add(btnLapReset);
pnlBot.setLayout(new GridLayout(1,1));
pnlBot.add(lstLaps);
add(pnlTop);
add(pnlBot);
btnGo.addActionListener(new btnGoListener());
btnReset.addActionListener(new btnResetListener());
btnSplit.addActionListener(new btnSplitListener());
btnSplitReset.addActionListener(new btnSplitResetListener());
btnLapAdd.addActionListener(new btnLapAddListener());
btnLapReset.addActionListener(new btnLapResetListener());
swThread.setDaemon(true);
ucThread.setDaemon(true);
swThread.start();
ucThread.start();
}

public static void main(String[] args) {
Clock applet = new Clock();
Frame aFrame = new Frame("计时器");
aFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
aFrame.add(applet, BorderLayout.CENTER);
aFrame.setSize(400, 200);
applet.init();
applet.start();
aFrame.setVisible(true);
}
}

❸ 如何用java实现一个计时器

java实现一个计时器,可以使用线程的sleep方法,实例如下:


{
Threadxc;
Dao=newDaoImpl();
publicTestDingShi()
{
xc=newThread(this);//线程开启
xc.start();
}
publicvoidrun()
{
while(true)
{
try
{
xc.sleep(1000);//睡眠开始计时
}
catch(InterruptedExceptione)
{
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
//TODO定时在此

}

}
}

❹ Java怎么给方法计时

你可以在开始和结束的时候,分别记录下当前的时间的这毫秒数。然后再减,以下是一段代码。

public class Test{
public static void main(String[] args) {
long startMili=System.currentTimeMillis();// 当前时间对应的毫秒数
System.out.println("开始 "+startMili);
// 执行一段代码,求一百万次随机值
for(int i=0;i<1000000;i++){
Math.random();
}
long endMili=System.currentTimeMillis();
System.out.println("结束 s"+endMili);
System.out.println("总耗时为:"+(endMili-startMili)+"毫秒");
}
}

❺ JAVA中如何使用计时函数

Java计时函数currentTimeMills()

System.currentTimeMills()计时精确到毫秒级,跟计算机以1970年1月1日0时为计时起点一样,该函数方法统计的也是从1970年1月1日0时开始,到程序运行到该函数时刻的毫秒总数。

该函数方法定义在Java系统类System中,如果想实现程序运行计时功能也很简单,只要在程序前后分别放置该函数方法,然后后减前毫秒总数,就能计算程序运行的耗时。具体实现如下:

long startTime = System.currentTimeMills(); //程序开始记录时间

//。。。 。。。

long endTime = System.currentTimeMills(); //程序结束记录时间

long TotalTime = endTime - startTime; //总消耗时间

❻ 用JAVA编写计时器

计时器可以使用timer类也可以使用线程类来操作,下面是Thread做的简单的计时器

{

publicstaticvoidmain(String[]args){
newCalculagraph().start();
}

privatelongnow=0l;

privatelongstart=System.currentTimeMillis();//程序启动时间的毫秒值

privatelongtime;

publicvoidrun(){
while(true){
now=System.currentTimeMillis();//获取一秒之后的毫秒值
time=now-start;//两个时间相减的到毫秒差
System.out.format("%02d:%02d:%02d ",
time/(1000*60*60)%60/*时*/,
time/(1000*60)%60/*分*/,
time/1000%60/*秒*/);//格式化字符串输出
try{
Thread.sleep(1000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
}

❼ java 时间现格式为00:00:00开始计时,如何表示

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

public class Test extends JFrame{

JLabel lbl=new JLabel();
Date now=new Date();
public Test() {

now.setHours(0);
now.setMinutes(0);
now.setSeconds(0);

Timer timer=new Timer(1000,new ActionListener(){

public void actionPerformed(ActionEvent e) {

Date now2=new Date(now.getTime()+1000);
now=now2;
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");

lbl.setText(formatter.format(now));
}

});
timer.start();

this.setLayout(new FlowLayout());
this.add(lbl);

this.setSize(300,200);
this.setVisible(true);
}
public static void main(String[] args) {
Test t=new Test();
}
}

❽ java计时代码,具体如下~

定时器计时->存入全局变量->程序开始->A页面读取全局变量时间->跳转B页面->B读取全局变量时间,这样没误差

❾ java中如何实现自动计时功能,就是点击一个start按钮就开始计时,以秒为单位

简单代码如下:

importjava.awt.Button;
importjava.awt.FlowLayout;
importjava.awt.Label;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjavax.swing.JFrame;
importjavax.swing.Timer;

@SuppressWarnings("serial")
{
finalLabellab=newLabel();
Datenow=newDate();
@SuppressWarnings("deprecation")
publicTimers(){
now.setHours(0);
now.setMinutes(0);
now.setSeconds(0);
setBounds(550,270,200,150);
finalTimertimer=newTimer(1000,newActionListener(){
publicvoidactionPerformed(ActionEvente){
Datenow2=newDate(now.getTime()+1000);
now=now2;
SimpleDateFormatformatter=newSimpleDateFormat("HH:mm:ss");
lab.setText(formatter.format(now));
}
});
Buttonb1=newButton("开始");
Buttonb2=newButton("停止");
b2.setBounds(40,40,40,40);
b1.setBounds(30,30,30,30);
b1.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
Buttonb=(Button)e.getSource();
b.setLabel("开始");
timer.start();
}
});
b2.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
Buttonb=(Button)e.getSource();
b.setLabel("停止");
timer.stop();
}
});

this.setLayout(newFlowLayout());
this.add(b2);
this.add(b1);
this.add(lab);

this.setSize(300,200);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
publicstaticvoidmain(String[]args){
Timerst=newTimers();
t.lab.setText("00:00:00");
}
}

不知是否帮到你,如满意请采纳!

❿ java计时

你可以在开始和结束的时候,分别记录下当前的时间的这毫秒数。然后再减,以下是一段代码。

public class Test{
public static void main(String[] args) {
long startMili=System.currentTimeMillis();// 当前时间对应的毫秒数
System.out.println("开始 "+startMili);
// 执行一段代码,求一百万次随机值
for(int i=0;i<1000000;i++){
Math.random();
}
long endMili=System.currentTimeMillis();
System.out.println("结束 s"+endMili);
System.out.println("总耗时为:"+(endMili-startMili)+"毫秒");
}
}

阅读全文

与java计时相关的资料

热点内容
苹果手机如何设置服务器 浏览:932
迅雷下载游戏需要解压 浏览:851
3d平滑命令 浏览:39
必须去车管所解压 浏览:385
室友命令我 浏览:308
lol全部命令 浏览:38
用什么APP查指数 浏览:919
什么是作品源码 浏览:669
我的理想程序员该怎么写 浏览:840
英译中国现代散文选pdf 浏览:446
装饰设计模式java 浏览:21
linuxshell清屏命令 浏览:134
惠利app是什么 浏览:779
游戏端口读取服务器失败怎么弄 浏览:878
linux修复mbr 浏览:128
磁盘格式化基本命令 浏览:578
程序员掉入异世界 浏览:954
andlua画质助手源码 浏览:577
winrar解压格式怎么看 浏览:147
qt编程入门pdf 浏览:599