1.11. Displaying Text in a Message Dialog Box
The program in Listing 1.1 displays
the text on the console, as shown in Figure
1.13. You can rewrite the program to display the text
in a message dialog box. To do so, you need to use the showMessageDialog
method in the JOptionPane
class. JOptionPane is one of the many predefined classes in the Java system
that you can reuse rather than "reinventing the wheel." You can use the showMessageDialog method to display any text in a message dialog box, as
shown in Figure 1.14. The new program is
given in Listing 1.2.
Figure 1.14. "Welcome to Java!" is displayed in a message box.
Listing 1.2. WelcomeInMessageDialogBox.java
1 /** This application program displays Welcome to Java! 2 * in a message dialog box. 3 */ 4 import javax.swing.JOptionPane; 5 6 public class WelcomeInMessageDialogBox { 7 public static void main(String[] args) { 8 // Display Welcome to Java! in a message dialog box 9 JOptionPane.showMessageDialog(null, "Welcome to Java!", 10 "Display Message", JOptionPane.INFORMATION_MESSAGE); 11 } 12 } |
This program uses a Java class JOptionPane (line 9). Java's predefined classes are grouped into
packages. JOptionPane
is in the javax.swing
package. JOptionPane
is imported to the program using the import statement in line 4 so that the compiler can locate the
class. Recall that you have used the System class in the statement System.out.println("Welcome
to Java"); in Listing 1.1. The
System class is not imported because it is in the java.lang
package. All the classes in the java.lang package are implicitly imported in every Java
program.
Note
The showMessageDialog
method is a static
method. Such a method should be invoked by using the class name followed by a
dot operator (.) and the method name with arguments. "Methods." The showMessageDialog method can be invoked with four arguments, as in
lines 9–10.
The first argument can always be
null.
null is a Java keyword that will be fully introduced in Part II,
"Object-Oriented Programming." The second argument can be a string for text to
be displayed. The third argument is the title of the message box. The fourth
argument can be JOptionPane.INFORMATION_MESSAGE, which causes the icon to be displayed in the message box.
Note
JOptionPane.showMessageDialog(null, x, y, JOptionPane.INFORMATION_MESSAGE);
where x is a string for the text to be displayed, and y is a string for the title of the message box. The other
is to use a statement like this one:
JOptionPane.showMessageDialog(null, x);
No comments:
Post a Comment