java关于Timer计时器的问题求解

java关于Timer计时器的问题求解,第1张

timer内部有TimerTask。TimerTask可以取消cancel()。取消了,但是还在timer内部。

timerpurge()移除取消了的任务。

所以 最好 cancel 之后调用 purge 然后 置空timer timer =null;

不调用timercancel(),timerTask线程会一直被执行,

调用timercancel(),timerTask也会执行完当次之后结束。

最好

if(timer!=null){

timercancel();

timerpurge();

timer=null;

}

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

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

form1setAlwaysOnTop(true);// 总是允许窗口置顶

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

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

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

package hkyexample;

import javaawtBorderLayout;

import javaawtContainer;

import javaawtGridLayout;

import javaawteventActionEvent;

import javaawteventActionListener;

import javaawteventKeyEvent;

import javaawteventWindowEvent;

import javaawteventWindowListener;

import javaio;

import javautil;

import javaxswingJButton;

import javaxswingJFrame;

import javaxswingJOptionPane;

import javaxswingJPanel;

import javaxswingJTextField;

import javaxswingplafOptionPaneUI;

public class Demo{

    static boolean isRuning=false;

    static boolean isFirst=true;

    static Integer hmsCounter=0;

    static int hour,minute,second;

    

    @SuppressWarnings("unchecked")

    public static void main(String[] args) throws Exception {

 

        JFrame form1 = new JFrame("Form1");

        form1setAlwaysOnTop(true);// 1)总是允许窗口置顶

        

        JTextField jTextField = new JTextField(10);

        jTextFieldsetSize(10, 10);

        jTextFieldsetText("0");

        jTextFieldsetEditable(false);

 

        JButton jButton = new JButton("开始");

        jButtonsetSize(10, 10);

 

        

        Thread thread = new Thread(new Runnable() {

            @Override

            public void run() {

                while (true) {

                    while(isRuning){

                     ++hmsCounter; 

                     //3)时分秒显示

                     hour=hmsCounter/3600;

                     minute=hmsCounter%3600/60;

                     second=hmsCounter%60;

                        jTextFieldsetText(hour+"时"+minute+"分"+second+"秒");

                        try {Threadsleep(1000);} catch (Exception e2) {}

                    }

                    try {Threadsleep(200);} catch (Exception e2) {}// 修复上一次回答的版本可能会存在的Bug

                }

            }

        });

        jButtonsetMnemonic(KeyEventVK_ENTER);// 2)给JButton发送 Alt+Enter快捷键

        jButtonaddActionListener(new ActionListener() {

            @Override

            public void actionPerformed(ActionEvent e) {

               String text=jButtongetText()equals("开始")"暂停":"开始";

               jButtonsetText(text);

               isRuning=!isRuning;

               if(isFirst){

                   threadstart();

                   isFirst=false;

               }

            }

        });

 

        JPanel panel = new JPanel();

        panelsetSize(200, 200);

        paneladd(jTextField, BorderLayoutNORTH);

        paneladd(jButton, BorderLayoutCENTER);

        form1add(panel);

        form1setBounds(200, 100, 250, 150);

        form1setDefaultCloseOperation(JFrameEXIT_ON_CLOSE);

        form1addWindowListener(new WindowListener() {

            @Override

            public void windowOpened(WindowEvent e) {

                // TODO Auto-generated method stub

                 

            }

             

            @Override

            public void windowIconified(WindowEvent e) {

                // TODO Auto-generated method stub

                 

            }

             

            @Override

            public void windowDeiconified(WindowEvent e) {

                // TODO Auto-generated method stub

                 

            }

             

            @Override

            public void windowDeactivated(WindowEvent e) {

                // TODO Auto-generated method stub

                 

            }

             

            @Override

            public void windowClosing(WindowEvent e) {

               // 窗口关闭前取出文本框的数字保存到外部文件,代码在此处写

                JOptionPaneshowMessageDialog(null, "Are you sure closing");

            }

             

            @Override

            public void windowClosed(WindowEvent e) {

                // TODO Auto-generated method stub

                 

            }

             

            @Override

            public void windowActivated(WindowEvent e) {

                // TODO Auto-generated method stub

                 

            }

        });

        

        form1setVisible(true);

    }

}

import javautil;

import javaawt;

import javaawtevent;

import javaapplet;

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 javaawtList lstLaps = new javaawtList();

private final UpdateClockThread ucThread = new UpdateClockThread();

private final StopwatchThread swThread = new StopwatchThread();

private class btnGoListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

if ((btnGogetLabel()equals("开始")) ||

(btnGogetLabel()equals("继续"))) {

// Start the clock!

swThreadgo();

btnGosetLabel("停止");

btnGosetBackground(Colorred);

} else if (btnGogetLabel()equals("停止")) {

// Stop the clock!

swThreadnoGo();

btnGosetLabel("继续");

btnGosetBackground(Colorgreen);

}

}

}

private class btnResetListener implements ActionListener {

/ Actually run when the button gets clicked

@param e The event

/

public void actionPerformed(ActionEvent e) {

swThreadreset();

btnGosetLabel("开始");

btnGosetBackground(Colorgreen);

}

}

/ 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) {

lblSplitsetText(lblWatchgetText());

}

}

/ 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) {

lblSplitsetText("");

}

}

/ 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) {

swThreadaddLap();

}

}

/ 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) {

swThreadresetLap();

}

}

/ 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 = CalendargetInstance();

String month = IntegertoString(nowget(CalendarMONTH)+1);

String date = IntegertoString(nowget(CalendarDAY_OF_MONTH));

String year = IntegertoString(nowget(CalendarYEAR));

String hour = IntegertoString(nowget(CalendarHOUR));

if (hourequals("0")) hour = "12";

String minute = IntegertoString(nowget(CalendarMINUTE));

if (minutelength() == 1) minute = "0" + minute;

String second = IntegertoString(nowget(CalendarSECOND));

if (secondlength() == 1) second = "0" + second;

String ampm = nowget(CalendarAM_PM) == CalendarAM

"AM" : "PM";

lblDatesetText(month + "/" + date + "/" + year);

lblTimesetText(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() - startDategetTime() : 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 = LongtoString(time % 1000);

while (mslength() < 3)

ms = "0" + ms;

ms = mssubstring(0, mslength() - 1);

time /= 1000;

sec = LongtoString(time % 60);

if (seclength() == 1) sec = "0" + sec;

time /= 60;

min = LongtoString(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();

lstLapsadd("冲线 " + IntegertoString(++lapNum)+ " -- " +

"用时: " + msToString(elapsed) + " -- " +

"冲线时间: " + msToString(elapsed - lastLapTime));

lastLapTime = elapsed;

}

/ Resets the lap list

/

public void resetLap() {

lstLapsremoveAll();

lapNum = 0;

lastLapTime = 0;

}

/ Main code of the thread

/

public void run() {

while (true) {

lblWatchsetText(msToString(elapsedTime()));

yield();

}

}

}

public void init() {

setLayout(new GridLayout(2,1));

setBackground(ColorlightGray);

setForeground(Colorblack);

pnlTopsetLayout(new GridLayout(4,4));

pnlTopadd(new Label("日期:"));

pnlTopadd(lblDate);

pnlTopadd(new Label("时间:"));

pnlTopadd(lblTime);

pnlTopadd(new Label("计时:"));

//lblWatchsetBackground(Colorblack);

lblWatchsetForeground(Colorblue);

pnlTopadd(lblWatch);

pnlTopadd(btnGo);

btnGosetBackground(Colorgreen);

pnlTopadd(btnReset);

pnlTopadd(new Label("定点:"));

pnlTopadd(lblSplit);

pnlTopadd(btnSplit);

pnlTopadd(btnSplitReset);

pnlTopadd(new Label("冲线时间:"));

pnlTopadd(new Label());

pnlTopadd(btnLapAdd);

pnlTopadd(btnLapReset);

pnlBotsetLayout(new GridLayout(1,1));

pnlBotadd(lstLaps);

add(pnlTop);

add(pnlBot);

btnGoaddActionListener(new btnGoListener());

btnResetaddActionListener(new btnResetListener());

btnSplitaddActionListener(new btnSplitListener());

btnSplitResetaddActionListener(new btnSplitResetListener());

btnLapAddaddActionListener(new btnLapAddListener());

btnLapResetaddActionListener(new btnLapResetListener());

swThreadsetDaemon(true);

ucThreadsetDaemon(true);

swThreadstart();

ucThreadstart();

}

public static void main(String[] args) {

Clock applet = new Clock();

Frame aFrame = new Frame("计时器");

aFrameaddWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

Systemexit(0);

}

});

aFrameadd(applet, BorderLayoutCENTER);

aFramesetSize(400, 200);

appletinit();

appletstart();

aFramesetVisible(true);

}

}

以上就是关于java关于Timer计时器的问题求解全部的内容,包括:java关于Timer计时器的问题求解、JAVA需要一条秒表计时器代码、JAVA计时器的JAVA代码等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zz/9489502.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-28
下一篇 2023-04-28

发表评论

登录后才能评论

评论列表(0条)

保存