简体   繁体   English

使Swing Timer执行N次?

[英]Make a Swing Timer execute N times?

How can I adjust this Timer code so that it executes four times and then stops? 如何调整此Timer代码,使其执行四次然后停止?

timer = new Timer(1250, new java.awt.event.ActionListener() {
    @Override
    public void actionPerformed(java.awt.event.ActionEvent e) {
         System.out.println("Say hello");
    }
});
timer.start();

You could do: 您可以这样做:

Timer timercasovac = new Timer(1250, new ActionListener() {
    private int counter;

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Say hello");
        counter++;
        if (counter == 4) {
            ((Timer)e.getSource()).stop();
        }
    }
});
timercasovac.start();

You need to count yourself and then stop the Timer manually: 您需要盘点自己,然后手动停止Timer

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

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class TestTimer {

    private int count = 0;
    private Timer timer;
    private JLabel label;

    private void initUI() {
        JFrame frame = new JFrame("test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        label = new JLabel(String.valueOf(count));
        frame.add(label);
        frame.pack();
        frame.setVisible(true);
        timer = new Timer(1250, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (count < 4) {
                    count++;
                    label.setText(String.valueOf(count));
                } else {
                    timer.stop();
                }
            }
        });
        timer.start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestTimer().initUI();
            }
        });
    }

}

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

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