为什么 Java 的 Swing 计时器类不起作用?

huangapple go评论161阅读模式
英文:

Why does java swing timer class not work?

问题

以下是您的代码的翻译部分:

这是我的主类:

import javax.swing.Timer;

public class Test {
    public static int k=9;
    public static void main(String[] args) {
        
        Timer t = new Timer(100, new Loop());
        t.start();
    }  
}

以及实现了ActionListener接口的我的类Loop

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Loop implements ActionListener {    
    @Override
    public void actionPerformed(ActionEvent e) {
       if(Test.k==9){
           System.out.println("它正在工作");
       } 
    }
}

我不知道为什么?当我已经完全满足它的需求,但它不会在控制台打印“它正在工作”。

还有一个问题是:“这个Timer类和Java中的Thread类类似吗?”

感谢您的回答!

英文:

Here is my main class

import javax.swing.Timer;

public class Test {
    public static int k=9;
    public static void main(String[] args) {
        
        Timer t = new Timer(100, new Loop());
        t.start();
    }  
}

And my class Loop which implements ActionListener

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Loop implements ActionListener {    
    @Override
    public void actionPerformed(ActionEvent e) {
       if(Test.k==9){
           System.out.println("Its's Working");
       } 
    }
    
}

I don't know why? When I've fully what it need but it doesn't print "Its's Working" in the console

And one more question is that "Is this Timer class similar to Thread in java ?"

Thanks for your answer!

答案1

得分: 1

你的程序在设置定时器后立即退出,没有机会触发定时器。

AWT事件分派线程(EDT)需要以某种原因启动,以使定时器保持活动状态。

Swing应该从此线程中使用。如果你这样做,它应该能正常工作。

java.awt.EventQueue.invokeLater(() -> {     
    Timer t = new Timer(100, new Loop());
    t.start();
});

为了避免缩进大量的代码,并且拥有一个简短的main方法,我倾向于创建一个名为go的方法并使用方法引用。

java.awt.EventQueue.invokeLater(Test::go);

private static void go() {
英文:

Your program exits immediately after stating the timer, giving it no chance to fire.

The AWT Event Dispatch Thread (EDT) will need to have started for some reason in order for the timer to stay alive.

Swing is supposed to be use from this thread. If you do so, it should work.

    java.awt.EventQueue.invokeLater(() -> {     
        Timer t = new Timer(100, new Loop());
        t.start();
    });

To avoid indenting a lot of code , and to have a short main, I tend to create a method call go and use a method reference.

java.awt.EventQueue.invokeLater(Test::go);

private static void go() {

huangapple
  • 本文由 发表于 2020年10月27日 12:53:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64548491.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定