How do I flash the window taskbar in Swing?

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class WindowTaskbarFlash extends JFrame {
    private WindowTaskbarFlash() throws HeadlessException {
        initUI();
    }

    private void initUI() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        pack();
        setSize(200, 200);
        setState(Frame.ICONIFIED);

        // Demonstrate flashes the application window task bar
        // by calling the toFront method every 5 seconds.
        Timer timer = new Timer(5000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                toFront();
            }
        });
        timer.start();
    }

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

How do I calculate process execution time in higher resolution?

This example demonstrates how to use the System.nanoTime() method to calculate processing execution time in higher resolution. The processing time calculated in nanoseconds resolution.

package org.kodejava.example.lang;

public class NanoSecondsTimerResolution {
    public static void main(String[] args) {
        // Get process execution start time in nanoseconds.
        long start = System.nanoTime();
        System.out.println("Process start... " + start);

        try {
            Thread.sleep(5000); // Simulate a long process.
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Get process execution finish time in nanoseconds.
        long finish = System.nanoTime();
        System.out.println("Process finish... " + finish);

        // Calculate the process execution time.
        long execTime = finish - start;
        System.out.println("Processing time = " + execTime + "(ns)");
    }
}

How do I set Swing Timer initial delay?

The Swing javax.swing.Timer object fires the action event after the delay time specified in the constructor passed. For some reasons you might want the Timer class fires immediately after it was started.

To achieve this you can set the timer initial delay by calling the setInitialDelay(int initialDelay) method. The example below give you an example how to do it.

package org.kodejava.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());

        // Set initial delay of the Timer object. Setting initial delay
        // to zero causes the timer fires the event immediately after
        // it is started.
        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();
            }
        }
    }
}

How do I use Swing Timer class?

In this example you’ll see how to use java.swing.Timer class to create a text clock program.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class TimerDemo extends JFrame {
    public static final DateFormat df = new SimpleDateFormat("hh:mm:ss");

    public TimerDemo() throws HeadlessException {
        initUI();
    }

    private void initUI() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(200, 200);

        Container container = getContentPane();
        container.setLayout(new FlowLayout(FlowLayout.CENTER));

        final JLabel label = new JLabel();
        container.add(label);

        Timer timer = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Calendar now = Calendar.getInstance();
                String timeText = "<html><font size=\"6\" color=\"blue\">" +
                    df.format(now.getTime()) +
                    "</font></html>";
                label.setText(timeText);
            }
        });
        timer.start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TimerDemo().setVisible(true);
            }
        });
    }
}

How do I create a scheduled task using timer?

This example show you how to create a simple class for scheduling a task using Timer and TimerTask class.

package org.kodejava.example.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerExample extends TimerTask {
    private DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");

    public static void main(String[] args) {
        // Create an instance of TimerTask implementor.
        TimerTask task = new TimerExample();

        // Create a new timer to schedule the TimerExample instance at a
        // periodic time every 5000 milliseconds (5 seconds) and start it
        // immediately
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(task, new Date(), 5000);
    }

    /**
     * This method is the implementation of a contract defined in the 
     * TimerTask class. This in the entry point of the task execution.
     */
    public void run() {
        // To make the example simple we just print the current time.
        System.out.println(formatter.format(new Date()));
    }
}

Here is the result printed by the code snippet above:

03:10:38 PM
03:10:43 PM
03:10:48 PM
03:10:53 PM
03:10:58 PM