我们在11-2节中已经介绍了JOptionPane的构造函数,虽然大部份的情况下我们只需要使用JOptionPane的静态方法来产生对话框 ,但如果你想直接使用JOptionPane对象来产生对话框,当然也可以.下面我们就举一个以JOptionPane对象产生对话框的范例:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import com.incors.plaf.alloy.*;
import com.incors.plaf.alloy.themes.glass.*;
public class OptionPaneDemo implements ActionListener {
JFrame f = null;
JLabel label = null;
public OptionPaneDemo() {
f = new JFrame("OptionPane Demo");
Container contentPane = f.getContentPane();
JButton b = new JButton("Show Text Input");
b.addActionListener(this);
label = new JLabel(" ", JLabel.CENTER);
contentPane.add(label, BorderLayout.NORTH);
contentPane.add(b, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
SwingUtil.setLookAndFeel();
new OptionPaneDemo();
}
public void actionPerformed(ActionEvent e) {
String title = "Input Dialog";
JLabel message = new JLabel("您最喜欢吃什么食物?", JLabel.CENTER);
int messageType = JOptionPane.QUESTION_MESSAGE;
int optionType = JOptionPane.OK_CANCEL_OPTION;
String result = "";
// 利用message,messageType,optionType来建立JOptionPane对象
JOptionPane optionPane = new JOptionPane(message, messageType,
optionType);
// 利用JOptionPane的setWandtsInput()方法,使对话框有一个输入字段让用户输入信息
optionPane.setWantsInput(true);
// 利用JOptionPane的setInitialSelectionValue()方法,使得输入字段上的初始值为"请输入";
optionPane.setInitialSelectionValue("请输入!");
// 利用JOptionPane的setInputValue()方法,使得当用户按下"Cancel"键或关闭对话框时,result的默认字符串为
// "你没有输入";
optionPane.setInputValue("您没有输入!");
JDialog dialog = optionPane.createDialog(f, title);
dialog.show();
// JOptionPane的getInputValue()方法可以取得用户输入的信息.
result = (String) optionPane.getInputValue();
label.setText("您输入:" + result);
}
}
class SwingUtil {
public static final void setLookAndFeel() {
try {
Font font = new Font("JFrame", Font.PLAIN, 12);
Enumeration keys = UIManager.getLookAndFeelDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
if (UIManager.get(key) instanceof Font) {
UIManager.put(key, font);
}
}
AlloyLookAndFeel.setProperty("alloy.isLookAndFeelFrameDecoration",
"true");
AlloyTheme theme = new GlassTheme();
LookAndFeel alloyLnF = new AlloyLookAndFeel(theme);
UIManager.setLookAndFeel(alloyLnF);
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
}
}