1. 使用JOptionPane
JOptionPane, 正如他的名字,他是一个pane,用来作为JDialog的content pane
他提供4种如下static method,去创建显示JDialog。
1.1 showMessageDialog
显示消息消息对话框,可以设置消息内容、标题、消息的样式、图标
1.2 showInputDialog
显示输入对话框,可以设置消息内容、标题、消息的样式、图标、可选择的输入值、初始输入值。
当“可选择的输入值”设置存在时显示下来列表,否则显示JText输入框。
1.3 showConfirmDialog
显示确认对话框, 可以设置消息内容、标题、option样式、消息的样式、图标
1.4 showOptionDialog
显示对话框,可以设置消息内容、标题、option样式、消息的样式、图标、可选择的输入值、初始输入值。
以上三种方法都是补充参数转而调用此方法。当需要改变option JButton上的文字,需要直接调用这个方法
这些static method会创建一个JOptionPane,然后创建JDialog,并将其content pane设置成前面创建的
JOptionPane。当此JOptionPane的value改变时,其property change listener会调用此JDialog的setVisual method。
消息的样式有ERROR_MESSAGE、INFORMATION_MESSAGE、WARNING_MESSAGE、QUESTION_MESSAGE、PLAIN_MESSAGE。
除了使用JOptionPane提供的四类static method。当功能不能满足时,比如屏保窗口修饰的关闭按钮功能、对输入的文本进行验证,可以手动创建
JOptionPane和JDialog,进行相应设置后将新建的JOptionPane作为新建的JDialog的content pane。最后调用新建的JDialog的pack和setVisual method去显示对话框。以下是样例,代码来源于Java指南
样例一:屏保窗口修饰的关闭按钮功能
final JOptionPane optionPane = new JOptionPane(
"The only way to close this dialog is by/npressing one of the following buttons./nDo you understand?",
JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION);
// You can't use pane.createDialog() because that
// method sets up the JDialog with a property change
// listener that automatically closes the window
// when a button is clicked.
final JDialog dialog = new JDialog(frame, "Click a button", true);
dialog.setContentPane( optionPane );
dialog.setDefaultCloseOperation( JDialog.DO_NOTHING_ON_CLOSE );
dialog.addWindowListener( new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we) {
setLabel("Thwarted user attempt to close window.");
}
});
optionPane.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if ( dialog.isVisible()
&& e.getSource()==optionPane
&& JOptionPane.VALUE_PROPERTY.equals(prop) ) {
//If you were going to check something
//before closing the window, you'd do
//it here.
dialog.setVisible(false);
dialog.dispose();
}
}
});
dialog.pack();
dialog.setLocationRelativeTo( frame );
dialog.setVisible( true );
int value = ((Integer)optionPane.getValue()).intValue();
if (value == JOptionPane.YES_OPTION) {
// Good
} else if (value == JOptionPane.NO_OPTION) {
// Try using the window decorations to close the non-auto-closing dialog. You can't!
} else {
// Window unavoidably closed (ESC?).
}
样例二:对输入的文本进行验证
定义JDialog
package components;
import javax.swing.JOptionPane;
import javax.swing.JDialog;
import javax.swing.JTextField;
import java.beans.*; //property change stuff
import java.awt.*;
import java.awt.event.*;
class CustomDialog extends JDialog implements ActionListener, PropertyChangeListener {
private String typedText = null;
private JTextField textField;
private String magicWord;
private JOptionPane optionPane;
private String btnString1 = "Enter";
private String btnString2 = "Cancel";
/**
* Returns null if the typed string was invalid;
* otherwise, returns the string as the user entered it.
*/
public String getValidatedText() {
return typedText;
}
/** Creates the reusable dialog. */
public CustomDialog(Frame aFrame, String aWord) {
super(aFrame, true);
magicWord = aWord.toUpperCase();
setTitle("Quiz");
textField = new JTextField(10);
//Create an array of the text and components to be displayed.
String msgString1 = "What was Dr. SEUSS's real last name?";
String msgString2 = "(The answer is /"" + magicWord + "/".)";
Object[] array = {msgString1, msgString2, textField};
//Create an array specifying the number of dialog buttons
//and their text.
Object[] options = {btnString1, btnString2};
//Create the JOptionPane.
optionPane = new JOptionPane(array,
JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null,
options, options[0]);
//Make this dialog display it.
setContentPane( optionPane );
//Handle window closing correctly.
setDefaultCloseOperation( DO_NOTHING_ON_CLOSE );
addWindowListener( new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we) {
/*
* Instead of directly closing the window,
* we're going to change the JOptionPane's
* value property.
*/
optionPane.setValue( JOptionPane.CLOSED_OPTION );
}
});
//Ensure the text field always gets the first focus.
addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent ce) {
textField.requestFocusInWindow();
}
});
//Register an event handler that puts the text into the option pane.
textField.addActionListener(this);
//Register an event handler that reacts to option pane state changes.
optionPane.addPropertyChangeListener(this);
}
/** This method handles events for the text field. */
public void actionPerformed(ActionEvent e) {
optionPane.setValue(btnString1);
}
/** This method reacts to state changes in the option pane. */
public void propertyChange(PropertyChangeEvent e) {
String propName = e.getPropertyName();
if ( isVisible()
&& e.getSource()==optionPane
&& (JOptionPane.VALUE_PROPERTY.equals(propName) || JOptionPane.INPUT_VALUE_PROPERTY.equals(propName))) {
Object value = optionPane.getValue();
if (value == JOptionPane.UNINITIALIZED_VALUE) {
//ignore reset
return;
}
//Reset the JOptionPane's value.
//If you don't do this, then if the user
//presses the same button next time, no
//property change event will be fired.
optionPane.setValue( JOptionPane.UNINITIALIZED_VALUE );
if ( btnString1.equals(value) ) {
typedText = textField.getText();
if ( magicWord.equalsIgnoreCase(typedText) ) {
//we're done; clear and dismiss the dialog
clearAndHide();
} else {
//text was invalid
textField.selectAll();
JOptionPane.showMessageDialog( this, "Sorry, /"" + typedText + "/" isn't a valid response./nPlease enter " + magicWord + ".", "Try again",
JOptionPane.ERROR_MESSAGE );
typedText = null;
textField.requestFocusInWindow();
}
} else { //user closed dialog or clicked cancel
// It's OK. We won't force you to type magicWord;
typedText = null;
clearAndHide();
}
}
}
/** This method clears the dialog and hides it. */
public void clearAndHide() {
textField.setText(null);
setVisible(false);
dispose();
}
}
调用
customDialog = new CustomDialog(frame, "geisel", this);
customDialog.pack();
customDialog.setLocationRelativeTo(frame);
customDialog.setVisible(true);
String s = customDialog.getValidatedText();
if (s != null) {
//The text is valid.
}
2. 使用JDialog
手动创建JDialog及其content pane, 然后调用其pack和setVisual method去显示对话框。