How do I use SwingWorker to perform background tasks?

This demo gives examples of using the SwingWorker class. The purpose of SwingWorker is to implement a background thread that you can use to perform time-consuming operations without affecting the performance of your program’s GUI.

package org.kodejava.swing;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;
import java.awt.Dimension;
import java.awt.FlowLayout;

public class SwingWorkerDemo extends JFrame {

    public SwingWorkerDemo() {
        initialize();
    }

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

    private void initialize() {
        this.setLayout(new FlowLayout());
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JButton processButton = new JButton("Start");
        JButton helloButton = new JButton("Hello");

        processButton.addActionListener(event -> {
            LongRunProcess process = new LongRunProcess();
            try {
                process.execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        helloButton.addActionListener(e ->
            JOptionPane.showMessageDialog(null, "Hello There"));

        this.getContentPane().add(processButton);
        this.getContentPane().add(helloButton);

        this.pack();
        this.setSize(new Dimension(500, 500));
    }

    static class LongRunProcess extends SwingWorker<Integer, Integer> {
        protected Integer doInBackground() {
            int result = 0;
            for (int i = 0; i < 10; i++) {
                try {
                    result += i * 10;
                    System.out.println("Result = " + result);

                    // Sleep for a while to simulate a long process
                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return result;
        }

        @Override
        protected void done() {
            System.out.println("LongRunProcess.done");
        }
    }
}

How do I know if a date is after another date?

This example demonstrate Date‘s class after() method to check if a date is later than another date.

package org.kodejava.util;

import java.util.Date;
import java.util.Calendar;

public class DateCompareAfter {
    public static void main(String[] args) {
        // Get current date
        Date today = new Date();

        // Add 1 day from the current date.
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1);
        Date tomorrow = calendar.getTime();

        // Tests if this date is after the specified date. This method will
        // return true if the value time represented by the tomorrow object
        // is later than today.
        if (tomorrow.after(today)) {
            System.out.println(tomorrow + " is after " + today);
        }
    }
}

The result of the code snippet above is:

Tue Oct 05 20:52:34 CST 2021 is after Mon Oct 04 20:52:33 CST 2021

How do I know if a date is before another date?

This example demonstrate Date‘s class before() method to check if a date is earlier than another date.

package org.kodejava.util;

import java.util.Date;
import java.util.Calendar;

public class DateCompareBefore {
    public static void main(String[] args) {
        // Get current date
        Date today = new Date();

        // Subtract 1 day from the current date.
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        Date yesterday = calendar.getTime();

        // Tests if this date is before the specified date. This method will
        // return true if the value time represented by the yesterday object
        // is earlier than today.
        if (yesterday.before(today)) {
            System.out.println(yesterday + " is before " + today);
        }
    }
}

The result of the code snippet above is:

Sun Oct 03 20:49:36 CST 2021 is before Mon Oct 04 20:49:36 CST 2021

How do I create an inner class?

An inner class is a class defined inside another class. Inner classes can, in fact, be constructed in several contexts. An inner class defined as a member of a class can be instantiated anywhere in that class. An inner class defined inside a method can only be referred to later in the same method. Inner classes can also be named or anonymous.

package org.kodejava.basic;

public class InnerClassDemo {
    private Bean bean;

    /**
     * Inner class, the compiled class will be named InnerClassDemo$Bean.class
     */
    class Bean {
        public int width;
        public int height;

        @Override
        public String toString() {
            return width + " x " + height;
        }
    }

    public InnerClassDemo() {
        Bean bean = new Bean();
        bean.width = 100;
        bean.height = 200;

        this.bean = bean;
    }

    public Bean getBean() {
        return this.bean;
    }

    public static void main(String[] args) {
        InnerClassDemo inner = new InnerClassDemo();
        System.out.println("inner.getBean() = " + inner.getBean());
    }
}

How do I clone an object?

To enable our object to be cloned we need to override Object class clone method. We can also add a java.lang.Cloneable interface to our class, this interface is an empty interface. When we call the clone() method we need the add a try-catch block to catch the CloneNotSupportedException. This exception will be thrown if we tried to clone an object that doesn’t suppose to be cloned.

Calling the clone() method does a stateful, shallow copy down inside the Java Virtual Machine (JVM). It creates a new object and copies all the fields from the old object into the newly created object.

package org.kodejava.basic;

public class CloneDemo implements Cloneable {
    private int number;
    private transient int data;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public static void main(String[] args) {
        CloneDemo clone = new CloneDemo();
        clone.number = 5;
        clone.data = 1000;

        try {
            // Create a clone of CloneDemo object. When we change the value of
            // number and data field in the cloned object it won't affect the
            // original object.
            CloneDemo objectClone = (CloneDemo) clone.clone();
            objectClone.number = 10;
            objectClone.data = 5000;

            System.out.println("cloned object = " + objectClone);
            System.out.println("origin object = " + clone);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }

    public String toString() {
        return "[number = " + number + "; data = " + data + "]";
    }
}