Java Swing计时器无法启动?

时间:2014-06-08 03:35:04

标签: java swing timer

我写了这个程序来测试Swing的计时器。它编译得很好并且没有运行时错误,但是一旦启动它就会停止并且屏幕上没有任何东西弹出。它是我在网上找到的示例代码的略微修改版本,因此它应该可以正常工作。我不知道代码有什么问题:

import java.awt.event.*;
import javax.swing.*;

public class Time 
{
int sec=0;
int min=0;

public Time()
{
    ActionListener taskPerformer = new ActionListener()
    {
        int sec=0;
        int min=0;
        public void actionPerformed(ActionEvent evt) 
        {
            if(sec==60)
            {
                sec = 0;
                min++;
            }
            System.out.println("Time passed: " + min + ":" + sec);
            if(min==2)
                System.exit(0);
        }
    };
    Timer timer = new Timer( 1000 , taskPerformer);
    timer.start();
}

public static void main(String[] args)
{
    Time timer = new Time();
}
}

1 个答案:

答案 0 :(得分:2)

javax.swing.Timer在其核心使用daemon个帖子。这意味着一旦存在main方法,JVM就会终止。

您可以尝试使用java.util.Timer或创建某种帧以便启动EDT

旁注:

您没有递增sec变量

例如......

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Time {

    int sec = 0;
    int min = 0;

    public Time() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);

                ActionListener taskPerformer = new ActionListener() {
                    int sec = 0;
                    int min = 0;

                    public void actionPerformed(ActionEvent evt) {
                        if (sec >= 60) {
                            sec = 0;
                            min++;
                        }
                        System.out.println("Time passed: " + min + ":" + sec);
                        if (min == 2) {
                            System.out.println("Terminate");
                            System.exit(0);
                        }
                        sec++;
                    }
                };
                Timer timer = new Timer(1000, taskPerformer);
                timer.start();
            }
        });
    }

    public static void main(String[] args) {
        Time timer = new Time();
    }
}