In a graphical user interface (GUI) environment, there are roughly two types of forms: the frame window and the Dialog form (dialog window). In Java, we use the JFrame object as the frame form, using the JDialog object as the dialog form. Here are some common ways to familiarize yourself with the Joptionpane class:
1. Joptionpane class method for output--showmesagedialog ()
Example (1)--Simple dialog window implementation:
Importjavax.swing.*;classshowmessage_test{ Public Static voidMain (string[] args) {JFrame JFrame; JFrame=NewJFrame (); Jframe.setsize (400,300); Jframe.settitle ("I Love Java"); Jframe.setvisible (true); Joptionpane.showmessagedialog (JFrame,"How is it?"); Joptionpane.showmessagedialog (NULL, "I ' m fine, thanks!"); }}
Operation Result:
On the left, the first parameter of the Showmessagedialog () method is a Frame object jframe, and the dialog form is displayed in the middle of the frame form; The first argument on the right shows the reserved word null, and the dialog appears in the center of the screen.
Example (2)--display first name and surname according to names:
1 Importjavax.swing.*;2 3 classshowmessage_test2{4 Public Static voidMain (string[] args) {5 String fullName, FirstName, lastName, space;6FullName =NewString ("Scott Chen");7Space =NewString ("");8 9FirstName = fullname.substring (0, Fullname.indexof (space));TenLastName = fullname.substring (Fullname.indexof (space) +1, Fullname.length ()); One AJoptionpane.showmessagedialog (NULL, "Your FirstName is:" +firstName); -Joptionpane.showmessagedialog (NULL, "Your LastName is:" +lastName); - the } -}
The program runs as shown and meets expectations.
2. Joptionpane class method for input--showinputdialog ()
Example (3)--Enter a name with a middle name and show the abbreviation:
1 Importjavax.swing.*;2 3 classshowinput_test{4 Public Static voidMain (string[] args) {5 String name, FirstName, MiddleName, LastName, Space, shortname;6Space =NewString ("");7 8Name = Joptionpane.showinputdialog (NULL, "Your Name:");9FirstName = name.substring (0, Name.indexof (space));Ten OneName = Name.substring (Name.indexof (space) +1, Name.length ()); AMiddleName = name.substring (0, Name.indexof (space)); -LastName = name.substring (Name.indexof (space) +1, Name.length ()); - theShortName = firstname.substring (0,1) + "." + middlename.substring (0,1) + "." + lastname.substring (0,1); -Joptionpane.showmessagedialog (NULL, shortname); - } -}
Using the indexof and substring methods together, you can divide a string into two strings, use two times to divide it into three strings, and run the results as expected.
Java Learning Joptionpane Class