Home » Desktop Java » swing » Timer » Java Swing Timer Example

About Ashraf Sarhan

Ashraf Sarhan
Ashraf Sarhan is a passionate software engineer, an open source enthusiast, has a Bsc. degree in Computer and Information Systems from Alexandria University. He is experienced in building large, scalable and distributed enterprise applications/service in multiple domains. He also has a keen interest in JavaEE, SOA, Agile and Big Data technologies.

Java Swing Timer Example

In this example we are going to demonstrate Java Swing Timer, A swing timer fires one or more ActionEvent at specified intervals. Swing timers are recommended than the general-purpose timers for GUI-related tasks for the following advantages:

  1. All swing timers share the same the preexisting timer thread which created by the first Timer object that executes.
  2. The GUI-related task automatically executes on the event-dispatch thread which means that it can safely manipulate the components.

 

1. Usages

  • Perform a task once, after a delay.
    For example, determine when to show a tool tip and when to hide it.
  • Perform a task repeatedly.
    For example, update a component that displays progress toward a goal.

2. How to use it

Setting up a timer involves the following:

  1. Creating a timer object.
  2. Registering one or more ActionListener on it to be notified when the timer “goes off” where the actionPerformed(ActionEvent e) method in this listener should contain the code for whatever task you need to be performed.
  3. Specifying the number of milliseconds between timer firings. If you want the timer to go off only once, you can invoke setRepeats(false) on the timer.
  4. To start the timer, call its start() method. To suspend it, call stop().

3. Swing Timers Example

Let’s look at an example of using a timer to periodically update a component that displays progress toward a goal.

DemoTask.java:

package com.jcg;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

/**
 * The Class SwingTimerDemo.
 *
 * @author ashraf
 */
@SuppressWarnings("serial")
public class SwingTimerDemo extends JPanel {
	
	private final static int ONE_SECOND = 1000;
    private final static String NEW_LINE_DLIM = "\n";

    private JProgressBar progressBar;
    private Timer timer;
    private JToggleButton jtButton;
    private DemoTask task;
    private JTextArea taskOutput;

    public SwingTimerDemo() {
        super(new BorderLayout());
        task = new DemoTask();

        //Create the demo's UI.
        jtButton = new JToggleButton("Start"); 
        jtButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (jtButton.isSelected()) {
					jtButton.setText("Stop");
					setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		            task.go();
		            timer.start();
				}else {
					jtButton.setText("Start");
					setCursor(null); //turn off the wait cursor
					task.pause();
					timer.stop();
				}  
			}
		});

        progressBar = new JProgressBar(0, task.getLengthOfTask());
        progressBar.setValue(0);
        progressBar.setStringPainted(true);

        taskOutput = new JTextArea(5, 20);
        taskOutput.setMargin(new Insets(5,5,5,5));
        taskOutput.setEditable(false);
        taskOutput.setCursor(null); 

        JPanel panel = new JPanel();
        panel.add(jtButton);
        panel.add(progressBar);

        add(panel, BorderLayout.PAGE_START);
        add(new JScrollPane(taskOutput), BorderLayout.CENTER);
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        //Create a timer.
        timer = new Timer(ONE_SECOND, new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                progressBar.setValue(task.getCurrent());
                String s = task.getMessage();
                if (s != null) {
                    taskOutput.append(s + NEW_LINE_DLIM);
                    taskOutput.setCaretPosition(
                            taskOutput.getDocument().getLength());
                }
                
                if (task.isDone()) {
                	jtButton.setSelected(false);
                	jtButton.setText("Start");
                    timer.stop();
                    setCursor(null); //turn off the wait cursor
                    progressBar.setValue(progressBar.getMinimum());
                }
            }
        });
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);

        //Create and set up the window.
        JFrame frame = new JFrame("SwingTimerDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new SwingTimerDemo();
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

SwingTimerDemo.java:

package com.jcg;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

/**
 * The Class SwingTimerDemo.
 *
 * @author ashraf
 */
@SuppressWarnings("serial")
public class SwingTimerDemo extends JPanel {
	
	private final static int ONE_SECOND = 1000;
    private final static String NEW_LINE_DLIM = "\n";

    private JProgressBar progressBar;
    private Timer timer;
    private JToggleButton jtButton;
    private DemoTask task;
    private JTextArea taskOutput;

    public SwingTimerDemo() {
        super(new BorderLayout());
        task = new DemoTask();

        //Create the demo's UI.
        jtButton = new JToggleButton("Start"); 
        jtButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (jtButton.isSelected()) {
					jtButton.setText("Stop");
					setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		            task.go();
		            timer.start();
				}else {
					jtButton.setText("Start");
					setCursor(null); //turn off the wait cursor
					task.pause();
					timer.stop();
				}  
			}
		});

        progressBar = new JProgressBar(0, task.getLengthOfTask());
        progressBar.setValue(0);
        progressBar.setStringPainted(true);

        taskOutput = new JTextArea(5, 20);
        taskOutput.setMargin(new Insets(5,5,5,5));
        taskOutput.setEditable(false);
        taskOutput.setCursor(null); 

        JPanel panel = new JPanel();
        panel.add(jtButton);
        panel.add(progressBar);

        add(panel, BorderLayout.PAGE_START);
        add(new JScrollPane(taskOutput), BorderLayout.CENTER);
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        //Create a timer.
        timer = new Timer(ONE_SECOND, new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                progressBar.setValue(task.getCurrent());
                String s = task.getMessage();
                if (s != null) {
                    taskOutput.append(s + NEW_LINE_DLIM);
                    taskOutput.setCaretPosition(
                            taskOutput.getDocument().getLength());
                }
                
                if (task.isDone()) {
                	jtButton.setSelected(false);
                	jtButton.setText("Start");
                    timer.stop();
                    setCursor(null); //turn off the wait cursor
                    progressBar.setValue(progressBar.getMinimum());
                }
            }
        });
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);

        //Create and set up the window.
        JFrame frame = new JFrame("SwingTimerDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new SwingTimerDemo();
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Output:

swing_timer

Figure 1: Swing Timer Demo

4. Download the Source Code

This was an example to show Java Swing Timer.

Download
You can download the full source code of this example here: SwingTimerExampleCode.zip
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of