Java Swing Timer仅运行一次

bro*_*rto 2 java swing timer

谁能告诉我为什么这个计时器只运行一次?

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

public class TimerTest implements ActionListener{

    private Robot r;
    private Timer t;
    private int i;

    public TimerTest(){     
        i = 0;  
        try {
            r = new Robot();
        } catch (AWTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
        t = new Timer(1000, this);  
        t.setRepeats(true);
        t.start();  
    }

    public static void main(String [] args){
        new TimerTest();        
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        i++;
        System.out.println("Action..." + i);        
    }
Run Code Online (Sandbox Code Playgroud)

有趣的是,如果我将Timer的延迟减少到仅100,它会按预期工作。甚至更有趣的是,如果我删除了初始化机器人的代码,那么它根本无法工作,则程序会在我运行时立即终止。

我已经在Windows 7和Ubuntu上进行了尝试(尽管在Ubuntu上我完全无法使用机器人,因为出现异常。也许是与权利有关的东西)。

Hal*_*arr 5

您的主电源已处理,因此程序停止了。您可以使用以下代码对其进行测试,并将其添加到TimerTest()

JFrame testFrame = new JFrame();
testFrame.setVisible(true);
testFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
Run Code Online (Sandbox Code Playgroud)

当您关闭Frame时,TimerTest结束时,该JFrame不会使您的主体陷入困境。到此结束您的主电源,导致主电源关闭。结束程序并停止摆动计时器。