❶ 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)+"毫秒");
}
}