showOptionDialog() - Displaying Option Dialog Boxes

This section provides a tutorial example on how to use the static method, showInputDialog(), to create and display input dialog boxes to take text string input from the user.

The fourth type of dialog boxes you can create and display with the javax.swing.JOptionPane class is the option dialog box. This can be done with the static method: answer = showOptionDialog(frame, message, title, 0, type, icon, options, default), where:

Here is an example program I wrote to test the showOptionDialog() method:

 * Copyright (c) 2014,, All Rights Reserved.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JOptionPaneOptionDialog implements ActionListener {
   JFrame myFrame = null;
   public static void main(String[] a) {
      (new JOptionPaneOptionDialog()).test();
   private void test() {
      myFrame = new JFrame("showOptionDialog() Test");
      Container myPane = myFrame.getContentPane();
      JButton myButton = new JButton("Show");
   public void actionPerformed(ActionEvent e) {
      int messageType = JOptionPane.QUESTION_MESSAGE;
      String[] options = {"Java", "C++", "VB", "PHP", "Perl"};
      int code = JOptionPane.showOptionDialog(myFrame, 
         "What language do you prefer?", 
         "Option Dialog Box", 0, messageType, 
         null, options, "PHP");
      System.out.println("Answer: "+code);

If you run this example, and click the Show button, you will see an input dialog box showing up like this:
Congirmation Dialog Box Input

Select "Perl" on the option dialog box. Repeat the test with the "Java" option button and the close dialog box icon. You will see some messages printed on the Java console window:

Answer: 4
Answer: 0
Answer: -1

Interesting notes about this tutorial example:

Sample programs listed in this section have been tested with JDK 1.6.0 to 1.8.0.

Last update: 2014.

Table of Contents

 About This Book

 Introduction of Java Swing Package

 Graphics Environment of the Local System

 JFrame - Main Frame Class

 JLabel - Swing Label Class

 JButton - Swing Button Class

 JRadioButton - Swing Radio Button Class

 JTextField - Swing Text Field Class

 Menu Bar, Menus, Menu Items and Listeners

 Creating Internal Frames inside the Main Frame

 Layout of Components in a Container

 LookAndFeel and UIManager

Option Dialog Boxes

 javax.swing.JOptionPane - Creating and Displaying Option Dialog Boxes

 showMessageDialog() - Displaying Message Dialog Boxes

 showConfirmDialog() - Displaying Confirmation Dialog Boxes

 Receiving Inputs from Confirmation Dialog Boxes

 showInputDialog() - Displaying Input Dialog Boxes

showOptionDialog() - Displaying Option Dialog Boxes

 showInternal*Dialog() - Displaying Internal Dialog Boxes

 createDialog() - Creating Dialog Boxes Directly

 JEditorPane - The Editor Pane Class

 SwingWorker - The Background Task Worker


 PDF Printing Version