You have used JOptionPane to create input and output dialog boxes. This section provides a comprehensive introduction to JOptionPane and other dialog boxes. A dialog box is normally used as a temporary window to receive additional information from the user or to provide notification that some event has occurred. Java provides the JOptionPane class, which can be used to create standard dialogs. You can also build custom dialogs by extending the JDialog class.
The JOptionPane class can be used to create four kinds of standard dialogs:
Message dialog shows a message and waits for the user to click OK.
Confirmation dialog shows a question and asks for confirmation, such as OK or Cancel.
Input dialog shows a question and gets the user's input from a text field, combo box, or list.
Option dialog shows a question and gets the user's answer from a set of options.
These dialogs are created using the static methods show Xxx Dialog and generally appear as shown in Figure 29.10(a).
For example, you can use the following method to create a message dialog box, as shown in Figure 29.10(b):
JOptionPane.showMessageDialog( null , "SSN not found" , "For Your Information" , JOptionPane.INFORMATION_MESSAGE);
A message dialog box displays a message that alerts the user and waits for the user to click the OK button to close the dialog. The methods for creating message dialogs are:
public static void showMessageDialog(Component parentComponent, Object message) public static void showMessageDialog(Component parentComponent, Object message, String title, int messageType) public static void showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon)
The parentComponent can be any component or null . The message is an object, but often a string is used. These two parameters must always be specified. The title is a string displayed in the title bar of the dialog with the default value "Message".
The messageType is one of the following constants:
JOptionPane.ERROR_MESSAGE JOptionPane.INFORMATION_MESSAGE JOptionPane.PLAIN_MESSAGE JOptionPane.WARNING_MESSAGE JOptionPane.QUESTION_MESSAGE
By default, messageType is JOptionPane.INFORMATION_MESSAGE. Each type has an associated icon except the PLAIN_MESSAGE type, as shown in Figure 29.11. You can also supply your own icon in the icon parameter.
The message parameter is an object. If it is a GUI component, the component is displayed. If it is a non-GUI component, the string representation of the object is displayed. For example, the following statement displays a clock in a message dialog, as shown in Figure 29.12:
JOptionPane.showMessageDialog( null , new StillClock(), "Current Time" , JOptionPane.PLAIN_MESSAGE);
A message dialog box displays a message and waits for the user to click the OK button to dismiss the dialog. The message dialog does not return any value. A confirmation dialog asks a question and requires the user to respond with an appropriate button. The confirmation dialog returns a value that corresponds to a selected button.
The methods for creating confirmation dialogs are:
public static int showConfirmDialog(Component parentComponent, Object message) public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType) public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType) public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon)
The parameters parentComponent , message , title , icon , and messageType are the same as in the showMessageDialog method. The default value for title is "Select an Option" and for messageType is QUESTION_MESSAGE . The optionType determines which buttons are displayed in the dialog. The possible values are:
JOptionPane.YES_NO_OPTION JOptionPane.YES_NO_CANCEL_OPTION JOptionPane.OK_CANCEL_OPTION
Figure 29.13 shows the confirmation dialogs with these options.
The showConfirmDialog method returns one of the following int values corresponding to the selected option:
JOptionPane.YES_OPTION JOptionPane.NO_OPTION
JOptionPane.CANCEL_OPTION JOptionPane.OK_OPTION JOptionPane.CLOSED_OPTION
These options correspond to the button that was activated, except for the CLOSED_OPTION , which implies that the dialog box is closed without buttons activated.
An input dialog box is used to receive input from the user. The input can be entered from a text field or selected from a combo box or a list. Selectable values can be specified in an array, and one of them can be designated as the initial selected value. If no selectable value is specified when an input dialog is created, a text field is used for entering input. If fewer than twenty selection values are specified, a combo box is displayed in the input dialog. If twenty or more selection values are specified, a list is used in the input dialog.
The methods for creating input dialogs are shown below:
public static String showInputDialog(Object message) public static String showInputDialog(Component parentComponent, Object message) public static String showInputDialog(Component parentComponent, Object message, String title, int messageType) public static Object showInputDialog(Component parentComponent, Object message, int messageType, Icon icon, Object[] selectionValues, Object initialSelectionValue)
The first three methods listed above use a text field for input, as shown in Figure 29.14(a). The last method listed above specifies an array of Object type as selection values in addition to an object specified as an initial selection. The first three methods return a String that is entered from the text field in the input dialog. The last method returns an Object selected from a combo box or a list. The input dialog displays a combo box if there are fewer than twenty selection values, as shown in Figure 29.14(b); it displays a list if there are twenty or more selection values, as shown in Figure 29.14(c).
Note
The showInputDialog method does not have the optionType parameter. The buttons for input dialog are not configurable. The OK and Cancel buttons are always used. |
An option dialog allows you to create custom buttons. You can create an option dialog using the following method:
public static int showOptionDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon, Object[] options, Object initialValue)
The buttons are specified using the options parameter. The initialValue parameter allows you to specify a button to receive initial focus. The showOptionDialog method returns an int value indicating the button that was activated. For example, here is the code that creates an option dialog, as shown in Figure 29.15:
int value = JOptionPane.showOptionDialog( null , "Select a button" , "Option Dialog" , JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null , new Object[]{ "Button 0" , "Button 1" , "Button 2" }, "Button 1" );
This section gives an example that demonstrates the use of JOptionPane dialogs. The program prompts the user to select the annual interest rate from a list in an input dialog, the number of years from a combo box in an input dialog, and the loan amount from an input dialog, and it displays the loan payment schedule in a text area inside a JScrollPane in a message dialog, as shown in Figure 29.16.
Here are the major steps in the program (Listing 29.5):
1. | Display an input dialog box to let the user select an annual interest rate from a list. |
2. | Display an input dialog box to let the user select the number of years from a combo box. |
3. | Display an input dialog box to let the user enter the loan amount. |
4. | Compute the monthly payment, total payment, and loan payment schedule, and display the result in a text area in a message dialog box. |
1 import javax.swing.*; 2 3 public class JOptionPaneDemo { 4 public static void main(String args[]) { 5 // Create an array for annual interest rates 6 Object[] rateList = new Object[ 25 ]; 7 int i = ; 8 for ( double rate = 5 ; rate <= 8 ; rate += 1.0 / 8 ) 9 rateList[i++] = new Double(rate); 10 11 // Prompt the user to select an annual interest rate 12 Object annualInterestRateObject = JOptionPane.showInputDialog( 13 null , "Select annual interest rate:", "JOptionPaneDemo" , 14 JOptionPane.QUESTION_MESSAGE, null , rateList, null ); 15 double annualInterestRate = 16 ((Double)annualInterestRateObject).doubleValue(); 17 18 // Create an array for number of years 19 Object[] yearList = { new Integer( 7 ), new Integer( 15 ), 20 new Integer( 30 )}; 21 22 // Prompt the user to enter number of years 23 Object numberOfYearsObject = JOptionPane.showInputDialog( null , 24 "Select number of years:", "JOptionPaneDemo" , 25 JOptionPane.QUESTION_MESSAGE, null , yearList, null ); 26 int numberOfYears = ((Integer)numberOfYearsObject).intValue(); 27 28 // Prompt the user to enter loan amount 29 String loanAmountString = JOptionPane.showInputDialog( null , 30 "Enter loan amount,\nfor example, 150000 for $150000" , 31 "JOptionPaneDemo" , JOptionPane.QUESTION_MESSAGE); 32 double loanAmount = Double.parseDouble(loanAmountString); 33 34 // Obtain monthly payment and total payment 35 Loan loan = new Loan( 36 annualInterestRate, numberOfYears, loanAmount); 37 double monthlyPayment = loan.getMonthlyPayment(); 38 double totalPayment = loan.getTotalPayment(); 39 40 // Prepare output string 41 String output = "Interest Rate: " + annualInterestRate + "%" + 42 " Number of Years: " + numberOfYears + " Loan Amount: $" 43 + loanAmount; 44 output += "\nMonthly Payment: " + "$" + 45 ( int )(monthlyPayment * 100 ) / 100.0 ; 46 output += "\nTotal Payment: $" + 47 ( int )(monthlyPayment * 12 * numberOfYears * 100 ) / 100.0 + "\n" ; 48 49 // Obtain monthly interest rate 50 double monthlyInterestRate = annualInterestRate / 1200 ; 51 52 double balance = loanAmount; 53 double interest; 54 double principal; 55 56 // Display the header 57 output += "\nPayment#\tInterest\tPrincipal\tBalance\n" ; 58 59 for (i = 1 ; i <= numberOfYears * 12 ; i++) { 60 interest = ( int )(monthlyInterestRate * balance * 100 ) / 100.0 ; 61 principal = ( int )((monthlyPayment - interest) * 100 ) / 100.0 ; 62 balance = ( int )((balance - principal) * 100 ) / 100.0 ; 63 output += i + "\t" + interest + "\t" + principal + "\t" + 64 balance + "\n" ; 65 } 66 67 // Display monthly payment and total payment 68 JScrollPane jsp = new JScrollPane( new JTextArea(output)); 69 jsp.setPreferredSize( new java.awt.Dimension( 400 , 200 )); 70 JOptionPane.showMessageDialog( null , jsp, 71 "JOptionPaneDemo" , JOptionPane.INFORMATION_MESSAGE, null ); 72 } 73 } |
The JOptionPane dialog boxes are modal , which means that no other window can be accessed until a dialog box is dismissed.
You have used the input dialog box to enter input from a text field. This example shows that input dialog boxes can also contain a list (lines 12 “14) or a combo box (lines 23 “25) to list input options. The elements of the list are objects. The return value from these input dialog boxes is of the Object type. To obtain a double value or an int value, you have to cast the return object into Double or Integer , then use the doubleValue or intValue method to get the double or int value (lines 15 “16 and 26).
You have already used the message dialog box to display a string. This example shows that the message dialog box can also contain GUI objects. The output string is contained in a text area, the text area is inside a scroll pane, and the scroll pane is placed in the message dialog box (lines 68 “71).