JOptionPane: Java dialog box showOptionDialog
Another type of dialog box in the java.swing.JOptionPane class is OptionDialog. It can display multiple buttons, a message, or a set of JButton components. This can be done with the following method:showOptionDialog(frame, message, title, typeOption, typeMessage icon options default), or:
- frame: is the parent Component;
- message: is the String message to display in the dialog;
- title: used as the title of the dialog box;
- typeOption: is an integer that represents the type of options in the dialog. Valid codes are: YES_NO_OPTION, YES_NO_CANCEL_OPTION, and OK_CANCEL_OPTION;
- typeMessage: is an integer that denotes the type of message defined in the JOptionPane: classINFORMATION_MESSAGE, WARNING_MESSAGE, ERROR_MESSAGE and PLAIN_MESSAGE;
- icon: is an ImageIcon icon to display;
- options; is a choice table that the user can perform;
- defaultor or initialvalue is the default value to select.
This code example implements a dialog box with options:
import javax.swing.JOptionPane;
public class OptionDialog {
public static void main(String[] args) {
int return = JOptionPane.showOptionDialog(null,
"Are you sure you want to continue?",
"Error",
//JOptionPane yes no
JOptionPane.YES_NO_OPTION,
JOptionPane.ERROR_MESSAGE,
null, null, null);
}
}
After running the program, you will have this dialog box with an error message and two "yes" and "no" choice buttons. You can schedule events, for example, when you click on the 'no' button, you exit the program with.
References:
herongyang: showOptionDialog() - Displaying Option Dialog Boxes
Java Doc: showOptionDialog method
System.exit(
0
)
:Control buttons in JOptionPane.showOptionDialog
If you want to add buttons or change values, you can do so by adding an array of objects as choice options and choosing the initial value that will be selected by default.import javax.swing.JOptionPane;Result:
public class OptionDialog {
public static void main(String[] args) {
Object[] choice={"18-25 years","26-35 years","36-45 years","46-55 years","56 years and older"};
int choice = JOptionPane.showOptionDialog(null,
"What's your age range?",
"Age range",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, choice, choice[0]);
}
}
References:
herongyang: showOptionDialog() - Displaying Option Dialog Boxes
Java Doc: showOptionDialog method