简体   繁体   English

为什么这个计时器不适用于 actionListener?

[英]Why doesn't this timer work for actionListener?

I want to create a program where each second it prints "tick" to the console.我想创建一个程序,它每秒将“滴答”打印到控制台。 I want to do this using the ActionListener interface.我想使用 ActionListener 接口来做到这一点。 I created a timer object with a delay of 1000 milli-seconds.我创建了一个延迟为 1000 毫秒的计时器对象。

This approach with ActionListener and Timer worked in other projects, but it doesn't here. ActionListener 和 Timer 的这种方法在其他项目中有效,但在此处无效。

I will appreciate it if someone could help me.如果有人可以帮助我,我将不胜感激。

package mainPackage;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.*;

public class Game extends Canvas implements ActionListener {
    
    Timer timer;
    
    public Game() {
        timer = new Timer(1000, this);
        timer.start();
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Tick");
    }
    
    public static void main(String[] args) {
        new Game();
    }

}

I am new to java, so I am sorry if this is a stupid question!我是java新手,所以如果这是一个愚蠢的问题,我很抱歉!

Thanks in advance!提前致谢!

I presume the problem is that your program is finishing immediately.我认为问题在于您的程序正在立即完成。 The swing Timer does not prevent your program from ending.摆动计时器不会阻止您的程序结束。 Try displaying a swing component.尝试显示摆动组件。 Your program should continue, and the timer run, while the component is visible.您的程序应该继续运行,并且计时器运行,而组件是可见的。

Alternatively you could use java.util.Timer instead of javax.swing.Timer .或者,您可以使用java.util.Timer而不是javax.swing.Timer The util Timer can create non-deamon threads , which should keep your program alive. util Timer 可以创建非守护线程,这应该使您的程序保持活动状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM