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

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

public class MessageDialogDemo extends JFrame {
    public MessageDialogDemo() throws HeadlessException {

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

        JButton button1 = new JButton("Click Me!");
        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent 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(new ActionListener() {
            public void actionPerformed(ActionEvent 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(new ActionListener() {
            public void actionPerformed(ActionEvent 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));

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

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.