java - N 次执行后停止 Swing 计时器

标签 java swing timer

我写了这个 Swing 计时器,它应该运行 10 次然后停止。但是,编译器表示 Timer 未初始化。我不想初始化它,也不需要初始化它( here 是一个未初始化但可以工作的示例)。怎么了?

public Enhanced() {
    Timer picTimer ;
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 422);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);


    JLabel lblTimer = new JLabel();
    lblTimer.setBounds(361, 67, 61, 16);
    contentPane.add(lblTimer);

    ActionListener a = new ActionListener() {
        int time=0;
        @Override
        public void actionPerformed(ActionEvent e) {


            System.out.println("hello");

            if (++time > 10) {
                picTimer.stop();
                System.exit(0);
            }
        }
    };
    picTimer = new Timer(1000,a);

}

最佳答案

有一种方法可以避免引用外部计时器变量。

计时器实际上是您的 ActionListener 每次收到的事件的。因此,您可以通过调用e.getSource()来访问它。

这样,您甚至不需要提前声明计时器:

ActionListener a = new ActionListener() {
    int time=0;
    @Override
    public void actionPerformed(ActionEvent e) {


        System.out.println("hello");

        if (++time > 10) {
            Timer timer = (Timer)e.getSource();
            timer.stop();
            System.exit(0);
        }
    }
};

new Timer(1000,a).start();

请注意,像这样调用 System.exit() 无论如何都会停止计时器。确实不建议这样调用System.exit()

关于java - N 次执行后停止 Swing 计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33618046/

相关文章:

string - 如何获得耗时(以毫秒为单位)

java - 谷歌游戏控制台 : 'Your app signing key' s encryption strength does not meet Google Play's recommended minimum standard'

JavaFX - 无法加载外部 CSS 主题

java - JScrollPane 内容不显示

java - 如何设置 JButton ArrayList 的属性?

Java 变色图形与定时器

java - org.hibernate.hql.ast.QuerySyntaxException : table not mapped

java - 从 GWT JSNI 调用 Java 方法

java - 如何使用另一个类的按钮更改 JLabel?

c - 用一个物理定时器模拟多个虚拟定时器