The instructions contained in this tutorial describe displaying the Standard Dialog Boxes in Java.
*NOTE*This tech-recipe simply shows how to use the code to display the dialog boxes. If you require a fully coded example including buttons and JFrame, please e-mail the address below.
There are many different dialog boxes that come standard with Java which include the following:
* General
* Warning
* Error
* Information
* Question/Confirmation
* Input
* Option (many variations on this one)
-The option of text, icon, and which button options to choose are all for you to decide, based on the type of dialog you choose.
In each exmaple below, the option this can be left as is, or -as is recommended- replaced with the name of the class/object that called it.
The First String will be the text displayed in the window, and the second String will be the title of the dialog. The main difference in the dialog types are the button options and the displayed icon.
General:
JOptionPane.showMessageDialog(this, “General msg”, “General”, JOptionPane.PLAIN_MESSAGE);
Warning:
JOptionPane.showMessageDialog(this, “A Warning msg.”, “Warning”, JOptionPane.WARNING_MESSAGE);
Error:
JOptionPane.showMessageDialog(this, “An Error msg!”, “Error”, OptionPane.ERROR_MESSAGE);
Information:
JOptionPane.showMessageDialog(this, “An Information msg”, “Information”, JOptionPane.INFORMATION_MESSAGE);
Question:
int result = JOptionPane.showConfirmDialog(this, “A Question?”, “Question”, JOptionPane.YES_NO_OPTION);
if (result == 0)
System.out.println(“YES”);
else
System.out.println(“NO”);
}
/*In this example, the optionPane returns a result (as do all the others), but if the result of the pane is 0, then “yes” was clicked. Otherwise, the values is 1. and “no” was clicked.
-A cancel button can also be added with .YES_NO_CANCEL_OPTION.
In this case, if cancel was clicked, 2 would be the result value */
Input:
String inputValue = JOptionPane.showInputDialog(“What to input”);
/*The text entered in this dialog will be returned into inputvalue */
Option: (buttons)
Object[] opt = { “Outstanding”, “Excellent”, “Good”, “Fair”, “Poor” };
int result = JOptionPane.showOptionDialog(this, “What do you think of this recipe?”, “Option”, JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, opt, options[0]);
/*null – no optional buttons
opt – name of an array of Strings to be displayed as the options
options[0] – the item to be highlighted as the default
result – will be the integer value in the array of the button pressed */
Option: (list)
Object[] opt = { “One”, “Two”, “Three”, “Four” };
Object selectedValue = JOptionPane.showInputDialog(this, “choose a value”, “Option”, JOptionPane.INFORMATION_MESSAGE, null, opt, options[1]);
/*null – no optional buttons
opt – name of an array of Strings to be displayed as the options
options[1] – the item to be displayed as the default
selectedValue – will be the Object selected */
Questions and Comments: [email protected]
-William. § (marvin_gohan)