JOptionPane: showMessageDialog and showInputDialog

Input and output using windows

How to do this depends on what type of application we are developing. If it is a Web application, we will use an html page, if it is an android application; an Activity, if it is a MS-DOS command line application we saw how to do it in the tutorial "Input and output console" and if it is a desktop application, we can use a window as we shall see in this tutorial.

JOptionPane

This class makes it really easy to display standards windows to show and request information to and from users. These windows called Dialogs, are displayed in a "Modal" way, which means that they block the application until they are closed.

JOptionPane is part of the Swing library for handling GUI. This library is very complex, but in this tutorial we will see enough to display and receive information to and from the user. We will learn about Swing in future tutorials.

 

showMessageDialog(Component parentComponent, Object message)

This method creates a window that displays a message delivered in the message parameter. The parentComponent parameter is to indicate the parent window. In this first tutorial we will use null for this parameter.

   import javax.swing.JOptionPane;
    
    public class HelloWorld {
        public static void main(String[] args) {
            JOptionPane.showMessageDialog(null, "Hello World");
        }
    }

Mensaje de alerta

String showInputDialog(Object message)

This method is a function that displays a window with a text box and two buttons: OK and Cancel. If we click "ok", we receive a String with the contents of the text box as the function return value. If we click "cancel", we will receive a null result.

Ventana de mensaje showinputdialog

The following example shows how we can use this Dialog:

  package com.edu4java.javatutorials;

import javax.swing.JOptionPane;

public class ShowInputDialogExample {
	public static void main(String[] args) {
		String name = JOptionPane.showInputDialog("Type your name please");
		JOptionPane.showMessageDialog(null, "Hello " + name);
	}
}

Summary

The JOptionPane methods; showMessageDialog and showInputDialog are a bit advanced for the level of our current course, but they are the simplest way of showing and receiving information for our next tutorials.

Here we can see the power of object-oriented programming, where sophisticated components can be handled in a simple way. JOptionPane hides all the complexity of the management of these windows.