英文:
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() {
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论