How do I flash the window taskbar in Swing?

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;

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

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new WindowTaskbarFlash().setVisible(true));
    }

    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, e -> toFront());
        timer.start();
    }
}

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.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.swing;

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

public class TimerInitialDelayDemo extends JFrame {
    private final JLabel counterLabel = new JLabel();

    private Timer timer = null;

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

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new TimerInitialDelayDemo().setVisible(true));
    }

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

        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();
    }

    class MyActionListener implements ActionListener {
        private int counter = 10;

        public void actionPerformed(ActionEvent e) {
            counter = counter - 1;
            String text = "<html><font size='14'>" +
                    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.swing;

import javax.swing.*;
import java.awt.*;
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();
    }

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

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

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

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

        Timer timer = new Timer(1000, e -> {
            Calendar now = Calendar.getInstance();
            String timeText =
                    "<html><font size='10' color='blue'>" +
                            df.format(now.getTime()) +
                            "</font></html>";
            label.setText(timeText);
        });
        timer.start();
    }
}

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.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 final 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:

09:53:28 AM
09:53:33 AM
09:53:38 AM
09:53:43 AM
09:53:48 AM