Using JOptionPane

advertisement
Comp313
Java Programming
Using JOptionPane
Three basic syntax option for Input Dialog box: (This method returns a String value)
JOptionPane.showInputDialog(String 1)
JOptionPane.showInputDialog(null, String 1)
JOptionPane.showInputDialog(null, String 1, String 2, Dialog Type)
Example code:
JOptionPane.showInputDialog(“Enter your name:”)
JOptionPane.showInputDialog(null, “Enter your name:”)
JOptionPane.showInputDialog(null, “Enter your name”, “Entry Form”,
JOptionPane.INFORMATION_MESSAGE)
Result:
String2
String1
Dialog
type
Conversion of String: Whatever the user enters will always be return to your code as a
String value. Therefore, if you want to keep it as a string, just store it in a String variable.
However, to use the information as another data type, you must convert the String to the
appropriate data type.
Example code:
String userInput;
//again identifier userInput solely for example purposes
userInput = JOptionPane.showInputDialog(“Enter”);



To use input as a String data value:
do nothing. Value is stored in String variable.
To convert input to integer:
int x = Integer.parseInt(userInput)
To convert input to double:
double x = Double.parseDouble(userInput)
(Note: Dialog types are JOptionPane.ERROR_MESSAGE,
JOptionPane.INFORMATION_MESSAGE, JOptionPane.PLAIN_MESSAGE,
JOptionPane.WARNING_MESSAGE and JOptionPane.QUESTION_MESSAGE.)
Using JOptionPane
Page 1 of 2
Comp313
Java Programming
Using JOptionPane
Two basic syntax options for Message Dialog box :
JOptionPane.showMessageDialog(null, String1);
JOptionPane.showMessageDialog(null, String1, String2, Dialog type);
String2
String1
Dialog
type
Example code/output of message dialog box with just a String output and default title
bar and dialog type:
JOptionPane.showMessageDialog(null, “This is a message with only two arguments”);
Example code/output of message dialog box with a String output, a title bar String and
dialog type: (Please note the three commas!)
JOptionPane.showMessageDialog(null, “This is a message with four arguments:”
+ “\nnull\na message\na title for the title bar\na specific “
+ “dialog type (icon)”, “This goes in title bar”,
JOptionPane.ERROR_MESSAGE);
Using JOptionPane
Page 2 of 2
Download