用java實現(xiàn)一個計時器的方法:
我們擁有10余年網(wǎng)頁設(shè)計和網(wǎng)站建設(shè)經(jīng)驗,從網(wǎng)站策劃到網(wǎng)站制作,我們的網(wǎng)頁設(shè)計師為您提供的解決方案。為企業(yè)提供網(wǎng)站設(shè)計制作、成都做網(wǎng)站、微信開發(fā)、小程序開發(fā)、手機網(wǎng)站制作、H5開發(fā)、等業(yè)務(wù)。無論您有什么樣的網(wǎng)站設(shè)計或者設(shè)計方案要求,我們都將富于創(chuàng)造性的提供專業(yè)設(shè)計服務(wù)并滿足您的需求。
publicclassTestDingShiimplementsRunnable
{
Threadxc;
Daodao=newDaoImpl();
publicTestDingShi()
{
xc=newThread(this);//線程開啟
xc.start();
}
publicvoidrun()
{
while(true)
{
try
{
xc.sleep(1000);//睡眠開始計時
}
catch(InterruptedExceptione)
{
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
//TODO定時在此
}
}
}
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("繼續(xù)"))) {
// Start the clock!
swThread.go();
btnGo.setLabel("停止");
btnGo.setBackground(Color.red);
} else if (btnGo.getLabel().equals("停止")) {
// Stop the clock!
swThread.noGo();
btnGo.setLabel("繼續(xù)");
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);
}
}
應(yīng)該用線程里面的Timer來控制package com.sy.game.test;
import java.util.Timer;
import java.util.TimerTask;
public class TimeTask {
public static void main(String[] args) {
TimeTask tTask=new TimeTask();
tTask.timeVoid();
}
public void timeVoid(){
final Timer timer = new Timer();
TimerTask tt=new TimerTask() {
@Override
public void run() {
System.out.println("到點啦!");
timer.cancel();
}
};
timer.schedule(tt, 3000);
}
}
整合的:
/*
* java倒計時器
* shiyang
* */
package com.sy.game.test;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
@SuppressWarnings("unused")
public class TimeController extends JFrame implements ActionListener {
private static final long serialVersionUID = 4603262282860990473L;
private static final int DEFAULT_WIDTH = 200;
private static final int DEFAULT_HEIGHT = 100;
private static final int width = Toolkit.getDefaultToolkit()
.getScreenSize().width;
private static final int height = Toolkit.getDefaultToolkit()
.getScreenSize().height;
private Container container;
private JButton btn;
private JTextField jtfTime;
private Timer tmr;
public TimeController() {
initComponents();
Timer tmr = new Timer(1000, this);
this.tmr = tmr;
setVisible(true);
}
private void initComponents() {
this.setTitle("SY秒表");
this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
this.setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocation((width - DEFAULT_WIDTH) / 2,
(height - DEFAULT_HEIGHT) / 2);
jtfTime = new JTextField("10");
btn = new JButton("開始倒計時");
container = getContentPane();
JPanel panel = new JPanel();
panel.add(btn);
panel.add(jtfTime);
this.add(panel);
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == btn) {
jtfTime.setText("10");
tmr.start();
} else {
int t;
t = Integer.parseInt(jtfTime.getText());
t--;
jtfTime.setText("" + t);
if (t = 0) {
tmr.stop();
}
}
}
public static void main(String[] args) {
TimeController timeController = new TimeController();
}
}
package?test;
import?java.util.*;
import?java.awt.*;
import?java.awt.event.*;
import?java.applet.*;
public?class?Test5?extends?Applet?{
private?final?Panel?pan?=?new?Panel();
private?final?Label?time?=?new?Label();
private?final?Button?btnGo?=?new?Button("開始");
private?final?Button?btnPouse?=?new?Button("暫停");
private?final?Button?btnReset?=?new?Button("復(fù)位");
private?final?StopwatchThread?swThread?=?new?StopwatchThread();
private?class?btnGoListener?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
???
swThread.go();
btnGo.setEnabled(false);
}
}
private?class?btnPouseListener?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
???if(btnGo.isEnabled()){
???return?;
???}
?if?(btnPouse.getLabel().equals("繼續(xù)"))?{
swThread.go();
btnPouse.setLabel("暫停");
}?else?if?(btnPouse.getLabel().equals("暫停"))?{
swThread.noGo();
btnPouse.setLabel("繼續(xù)");
}
}
}
private?class?btnResetListener?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
swThread.reset();
btnGo.setEnabled(true);
btnGo.setLabel("開始");
btnPouse.setLabel("暫停");
}
}
private?class?StopwatchThread?extends?Thread?{
private?boolean?going?=?false;
private?long?prevElapsed?=?0;
private?Date?startDate?=?new?Date();
private?long?elapsedTime()?{
return?prevElapsed?+
(going???new?Date().getTime()?-?startDate.getTime()?:?0);
}
private?String?msToString(long?time)?{
???System.out.println(time+"??"+((0*60+2)*1000+999));
if(((99*60+59)*1000+983)=time((99*60+59)*1000+999)=time){//((0*60+2)*1000+983)=time((0*60+2)*1000+999)=time
if?(time?%?1000??990)
time?+=?2;
swThread.noGo();
}
String?ms,?sec,?min;
if?(time?%?10?=?5)
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;
}
public?void?run()?{
while?(true)?{
time.setText(msToString(elapsedTime()));
yield();
}
}
}
public?void?init()?{
setLayout(new?GridLayout(2,2));
setBackground(Color.lightGray);
setForeground(Color.black);
pan.setLayout(new?GridLayout(3,2));
pan.add(new?Label("計時:"));
time.setForeground(Color.blue);
pan.add(time);
pan.add(btnGo);
pan.add(btnPouse);
pan.add(btnReset);
pan.add(new?Label());
add(pan);
btnGo.addActionListener(new?btnGoListener());
btnReset.addActionListener(new?btnResetListener());
btnPouse.addActionListener(new?btnPouseListener());
swThread.setDaemon(true);
swThread.start();
}
public?static?void?main(String[]?args)?{
Test5?applet?=?new?Test5();
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);
}
}
可以改變有注釋的那個if語句里面的值來判斷什么時候停止