Code for timer in java swing
import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import java.util.Date; public class TimerDemo extends JFrame implements ActionListener { ProgressMonitor progress; static int counter = 0; Timer timer; public SimpleDateFormat TIME = new SimpleDateFormat("HH:mm:ss"); private static final int START_TIME = 0000; int count = 100; public TimerDemo() { super("Progress bar timer Demo"); setSize(250, 100); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); progress = new ProgressMonitor(null, " ", "Initializing . . .", 00, 100); timer = new Timer(1000, this); timer.start(); progress.setNote("Operation left " + count + ""); setVisible(true); } public static void main(String args[]) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } UIManager.put("ProgressMonitor.progressText", "Demo"); new TimerDemo(); } public void actionPerformed(ActionEvent e) { // Invoked by the timer every half second. Simply place SwingUtilities.invokeLater(new Update()); } class Update implements Runnable { public void run() { if(progress.isCanceled()) { progress.close(); System.exit(1); } if(count ==0){ timer.stop(); } progress.setProgress(count); progress.setNote("Operation left " + TIME.format(new Date(count-- * 1000)) + ""); System.out.println(TIME.format(new Date(count-- * 1000))); --count; } } }
For more information,visit the following link:
Ads