1 import javax.swing.JOptionPane; // import class JOptionPane 2 3 public class Addition { 4 public static void main( String args[] ) 5 { 6 String firstNumber, // first string entered by user 7 secondNumber; // second string entered by user 8 int number1, // first number to add 9 number2, // second number to add 10 sum; // sum of number1 and number2 11 12 // read in first number from user as a string 13 firstNumber = 14 JOptionPane.showInputDialog( "Enter first integer" ); 15 16 // read in second number from user as a string 17 secondNumber = 18 JOptionPane.showInputDialog( "Enter second integer" ); 19 20 // convert numbers from type String to type int 21 number1 = Integer.parseInt( firstNumber ); 22 number2 = Integer.parseInt( secondNumber ); 23 24 // add the numbers 25 sum = number1 + number2; 26 27 // display the results 28 JOptionPane.showMessageDialog( 29 null, "The sum is " + sum, "Results", 30 JOptionPane.PLAIN_MESSAGE ); 31 32 System.exit( 0 ); // terminate the program 33 } 34 }
import javax.swing.JOptionPane导入类
主要用到四种消息提示框方法:
showConfirmDialog():确认对话框
showInputDialog():输入对话框
showMessageDialog():消息对话框
showOptionDialog():选择对话框
主要有五种消息类型,类型不同,图标不同:
• ERROR_MESSAGE
• INFORMATION_MESSAGE
• WARNING_MESSAGE
• QUESTION_MESSAGE
• PLAIN_MESSAGE
通过调用不同方法,并输入不同参数可以得到不同的对话框
参数及其含义:
parentComponent 对话框所在的容器
message 提示消息
title 标题
optionType 选择按钮类型
messageType 消息类型
icon 自定义消息图标
initialSelectionValue 默认选项或信息
selectionValues 选择选项
options 操作选项
showMessageDialog只有一个确定按钮;
showOptionDialog有两个选择按钮,有返回值是int型,0或者1,0代表是,1代表否;
showInputDialog有输入列表,并且可以将你选择的那个对象返回;