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 {

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

    private void initialize() {
        setSize(500, 500);

        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) {
            } else if (result == JOptionPane.NO_OPTION) {
                // Do nothing, continue to run the application

        setLayout(new FlowLayout(FlowLayout.CENTER));
Message Dialog Box with JOptionPane

Message Dialog Box with JOptionPane