How do I create a message dialog box?

This example demonstrate how to create a message dialog box using the JOptionPane class methods. In the code below you’ll see the use of JOptionPane.showMessageDialog(), JOptionPane.showInputDialog() and JOptionPane.showConfirmDialog().

package org.kodejava.swing;

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

public class MessageDialogDemo extends JFrame {
    public MessageDialogDemo() throws HeadlessException {
        initialize();
    }

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

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

        JButton button1 = new JButton("Click Me!");
        button1.addActionListener(e -> {
            // Show a message dialog with a text message
            JOptionPane.showMessageDialog((Component) e.getSource(),
                    "Thank you!");
        });

        JButton button2 = new JButton("What is your name?");
        button2.addActionListener(e -> {
            // Show an input dialog that will ask you to input some texts
            String text = JOptionPane.showInputDialog((Component) e.getSource(),
                    "What is your name?");
            if (text != null && !text.equals("")) {
                JOptionPane.showMessageDialog((Component) e.getSource(),
                        "Hello " + text);
            }
        });

        JButton button3 = new JButton("Close Application");
        button3.addActionListener(e -> {
            // Show a confirmation dialog which will ask to for a YES or NO
            // button.
            int result = JOptionPane.showConfirmDialog((Component) e.getSource(),
                    "Are you sure want to close this application?");
            if (result == JOptionPane.YES_OPTION) {
                System.exit(0);
            } else if (result == JOptionPane.NO_OPTION) {
                // Do nothing, continue to run the application
            }
        });

        setLayout(new FlowLayout(FlowLayout.CENTER));
        getContentPane().add(button1);
        getContentPane().add(button2);
        getContentPane().add(button3);
    }
}
Message Dialog Box with JOptionPane

Message Dialog Box with JOptionPane

How do I get the JFrame of a component?

This code snippet gives an example on how to get the JFrame of a component. In this example we try to get the JFrame from a button action listener event. To get the JFrame we utilize the SwingUtilities.getRoot() method and this will return the root component of the component tree in out small program below which is a JFrame.

Beside getting the JFrame, in this program we also do small stuff like changing the frame background color by a random color every time a user presses the “Change Frame Color” button.

package org.kodejava.swing;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.HeadlessException;

public class GetFrameDemo extends JFrame {
    public GetFrameDemo() throws HeadlessException {
        initialize();
    }

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

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

        this.setLayout(new FlowLayout(FlowLayout.CENTER));

        final JLabel rLabel = new JLabel("r: ");
        final JLabel gLabel = new JLabel("g: ");
        final JLabel bLabel = new JLabel("b: ");

        JButton button = new JButton("Change Frame Background Color");
        button.addActionListener(e -> {
            Component component = (Component) e.getSource();

            // Returns the root component for the current component tree
            JFrame frame = (JFrame) SwingUtilities.getRoot(component);

            int r = (int) (Math.random() * 255);
            int g = (int) (Math.random() * 255);
            int b = (int) (Math.random() * 255);

            rLabel.setText("r: " + r);
            gLabel.setText("g: " + g);
            bLabel.setText("b: " + b);

            frame.getContentPane().setBackground(new Color(r, g, b));
        });

        this.getContentPane().add(button);
        this.getContentPane().add(rLabel);
        this.getContentPane().add(gLabel);
        this.getContentPane().add(bLabel);
    }
}
Get Swing Root Component

Get Swing Root Component

How do I disable JFrame close button?

To disable the close operation on a JFrame, when user click the close icon on the JFrame, we can set the value of the default close operation to WindowConstants.DO_NOTHING_ON_CLOSE.

package org.kodejava.swing;

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

public class DisableCloseButtonDemo extends JFrame {
    public DisableCloseButtonDemo() throws HeadlessException {
        initialize();
    }

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

    private void initialize() {
        // WindowConstants.DO_NOTHING_ON_CLOSE tell JFrame instance to do
        // nothing when a window closing event occurs.
        this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

        JButton button = new JButton("Close");
        button.addActionListener(e -> System.exit(0));

        this.setLayout(new FlowLayout(FlowLayout.CENTER));
        this.setSize(new Dimension(500, 500));
        this.getContentPane().add(button);
    }
}

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 handle JFrame window events?

This example show you how to handle JFrame window events such as windowOpened, windowClosing, windowClosed, etc. For handling these events we need to add a WindowListener listener to the JFrame instance. Here we use the WindowAdapter abstract class and implement the method which event we want to handle.

package org.kodejava.swing;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class WindowListenerDemo extends JFrame {
    public WindowListenerDemo() {
        initializeComponent();
    }

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

    private void initializeComponent() {
        setSize(500, 500);
        setTitle("Window Listener");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        this.addWindowListener(new WindowAdapter() {
            // Invoked when a window has been opened.
            public void windowOpened(WindowEvent e) {
                System.out.println("Window Opened Event");
            }

            // Invoked when a window is in the process of being closed.
            // The close operation can be overridden at this point.
            public void windowClosing(WindowEvent e) {
                System.out.println("Window Closing Event");
            }

            // Invoked when a window has been closed.
            public void windowClosed(WindowEvent e) {
                System.out.println("Window Close Event");
            }

            // Invoked when a window is iconified.
            public void windowIconified(WindowEvent e) {
                System.out.println("Window Iconified Event");
            }

            // Invoked when a window is de-iconified.
            public void windowDeiconified(WindowEvent e) {
                System.out.println("Window Deiconified Event");
            }

            // Invoked when a window is activated.
            public void windowActivated(WindowEvent e) {
                System.out.println("Window Activated Event");
            }

            // Invoked when a window is de-activated.
            public void windowDeactivated(WindowEvent e) {
                System.out.println("Window Deactivated Event");
            }

            // Invoked when a window state is changed.
            public void windowStateChanged(WindowEvent e) {
                System.out.println("Window State Changed Event");
            }

            // Invoked when the Window is set to be the focused Window, which means
            // that the Window, or one of its sub components, will receive keyboard
            // events.
            public void windowGainedFocus(WindowEvent e) {
                System.out.println("Window Gained Focus Event");
            }

            // Invoked when the Window is no longer the focused Window, which means
            // that keyboard events will no longer be delivered to the Window or any of
            // its sub components.
            public void windowLostFocus(WindowEvent e) {
                System.out.println("Window Lost Focus Event");
            }
        });
    }
}