Java如何设置Swing Timer的初始延迟?
javax.swing.Timer在构造函数中指定的延迟时间过去之后,Swing对象将触发action事件。由于某些原因,您可能希望Timer该类在启动后立即触发。
为此,您可以通过调用setInitialDelay(intinitialDelay)方法来设置计时器的初始延迟。下面的示例为您提供了一个示例。
package org.nhooo.example.swing; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class TimerInitialDelayDemo extends JFrame { private JLabel counterLabel = new JLabel(); private Timer timer = null; public TimerInitialDelayDemo() throws HeadlessException { initUI(); } private void initUI() { setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setSize(200, 200); Container container = getContentPane(); container.setLayout(new FlowLayout(FlowLayout.CENTER)); container.add(counterLabel); timer = new Timer(1000, new MyActionListener()); //设置Timer对象的初始延迟。设置初始延迟 //为零会导致计时器在触发后立即触发事件 //它开始了。 timer.setInitialDelay(0); timer.start(); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new TimerInitialDelayDemo().setVisible(true); } }); } class MyActionListener implements ActionListener { private int counter = 10; public void actionPerformed(ActionEvent e) { counter = counter - 1; String text = "<html><font size=\"14\">" + String.valueOf(counter) + "</font></head>"; counterLabel.setText(text); if (counter == 0) { timer.stop(); } } } }