How to Use JOptionPane to Create Dialogs

JOptionPane enables you to create and customize various kinds of dialogs. With JOptionPane the dialogs can have customized dialog layout, icons, dialog title, dialog text and button text. In addition, JOptionPane allows you to customize the displaying component and its position where on the screen dialog display.

To create simple modal dialogs, you use static methods of JOptionPane showAbcDialog() for instanceshowMessageDialog(). If a dialog has to be in an internal frame you can use showInteralAbcDialog() for example showInternalMessageDialog(). In order to create modeless dialog you need to create new instance of JOptionPane and add it to a JDialog instance. And then you call method setVisible(true)  of the JDialog’s instance to make it visible on screen.

JOptionPane provides you with two useful static methods such as showMessageDialog() and showOptionDialog(). The showMessageDialog() method shows a very simple dialog with one button while showOptionDialog() method displays a highly customized dialogs with different buttons texts. Besides these methods, JOptionPane provides showConfirmDialog() method to ask users to confirm an action and showInputDialog() to get simple input from the users.

Example of Using Method showMessageDialog of JOptionPane

In this example, we use showMessageDialog() method of JOptionPane to show various simple dialog with one button and different icons which represent different message types such as information, warning, error and question message. When you click on each radio button, it will display corresponding message type.


Information Message

Warning Message

Error Message

Question Message

Example of Using Method showOptionDialog to Create Dialogs

In this example, we use showOptionDialog method to show question dialog with as yes/no and yes/no/cancel options.


JOptionPane showOptionDialog

JOptionPane showOptionDialog

  • Was this tutorial helpful ?
  • YesNo