By Tony Bevis on Friday, 20 October 2023
Category: Java

Java programming course: 14.17 JOptionPane

JOptionPane

The JOptionPane class provides a simple way of displaying standard dialogs that show informational, warning or error messages through its static convenience methods. Change the ShowDialogButtonListener inner class as follows:

The method showMessageDialog() is static and hence can be invoked directly on its class JOptionPane;

Four arguments are passed to the method:


You can click OK to close the dialog.

You should see the following after clicking the Show dialog button:

If you change the fourth argument to JOptionPane.WARNING_MESSAGE the icon will appear as follows:

Setting it instead to JOptionPane.ERROR_MESSAGE will give this icon:

If you don't want an icon then specify JOptionPane.PLAIN_MESSAGE.

Often, it is useful to ask the user a Yes/No question, and for this you can use another static method called showConfirmDialog(). Change the code inside the button listener to the following:


The dialog looks like this:

In the section on JDialog a simple entry box with a label, text field and button were constructed. For simple inputs like this there is another convenience method of JOptionPane called showInputDialog():

In the next series of lessons we will look at access modifiers and visibility.

Next lesson: 15.1 Access modifiers and visibility

Related Posts

Leave Comments