Posted on 2008-06-15 18:54
fcp 阅读(7818)
评论(0) 编辑 收藏 所属分类:
j2se 、
swing
简单的说这个类实现的就是一个messagebox,主要使用的是static的函数
不多说了,直接看例子
showMessageDialog
显示一个带有OK按钮的模态对话框。你能简单的指定显示的消息,图标,对话框标题。下面是几个使用showMessageDialog的例子
 |
//default title and icon
JOptionPane.showMessageDialog(frame,
"Eggs are not supposed to be green.",
"Message");


|
 |
//custom title, warning icon
JOptionPane.showMessageDialog(frame,
"Eggs are not supposed to be green.",
"Inane warning",
JOptionPane.WARNING_MESSAGE);


|
 |
//custom title, error icon
JOptionPane.showMessageDialog(frame,
"Eggs are not supposed to be green.",
"Inane error",
JOptionPane.ERROR_MESSAGE);


|
 |
//custom title, no icon
JOptionPane.showMessageDialog(frame,
"Eggs are not supposed to be green.",
"A plain message",
JOptionPane.PLAIN_MESSAGE);


|
 |
//custom title, custom icon
JOptionPane.showMessageDialog(frame,
"Eggs are not supposed to be green.",
"Inane custom dialog",
JOptionPane.INFORMATION_MESSAGE,
icon);


|
showOptionDialog
显示一个有特殊的按钮,消息,图标,标题的模态对话框。用这个函数,你可以改变显示在按钮上的文字。你还可以执行更多的个性化操作。
 |
//Custom button text
 Object[] options = {"Yes, please",
"No, thanks",
"No eggs, no ham!"};
int n = JOptionPane.showOptionDialog(frame,
"Would you like some green eggs to go "
+ "with that ham?",
"A Silly Question",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
|
个性化按钮的文字
![A yes/no dialog, in those words [but perhaps translated]](http://java.sun.com/docs/books/tutorial/figures/uiswing/components/CustomizingButtonTextMetal.png) |
//default icon, custom title
int n = JOptionPane.showConfirmDialog(
frame,
"Would you like green eggs and ham?",
"An Inane Question",
JOptionPane.YES_NO_OPTION);
|
 |
 Object[] options = {"Yes, please",
"No way!"};
int n = JOptionPane.showOptionDialog(frame,
"Would you like green eggs and ham?",
"A Silly Question",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, //do not use a custom Icon
options, //the titles of buttons
options[0]); //default button title
|
ShowXxxDialog中产生的窗体唯一的不返回整形的就是showInoutDialog,取而代之的是它返回一个Object类型。这个Object类型一般是一个String类型,反应了用户的输入。这是一个例子,用showInputdialog去创建一个让用户从三个字符串中选择一个字符串的窗口。

Object[] possibilities =
{"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
frame,
"Complete the sentence:\n"
+ "\"Green eggs and
\"",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
icon,
possibilities,
"ham");
//If a string was returned, say so.

if ((s != null) && (s.length() > 0))
{
setLabel("Green eggs and
" + s + "!");
return;
}
//If you're here, the return value was null/empty.
setLabel("Come on, finish the sentence!");
如果你不想去限制用户的输入,你可以?????或者指定null替代Object类型的数组。用java标准的界面风格,替代以后的结果是这样的:

Icons used by JOptionPane
(Java look and feel)
 |
 |
 |
 |
question |
information |
warning |
error |
(Windows look and feel)
 |
 |
 |
 |
question |
information |
warning |
error |
参考: http://java.sun.com/docs/books/tutorial/uiswing/components/dialog.html