Option Dialog可以让用户自定义对话框类型,比较具有弹性,最大的好处是可以改变按钮上的文字.我们来看下面的例子:
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 OptionDialog implements ActionListener {
JFrame f = null;
JLabel label = null;
public OptionDialog() {
f = new JFrame("OptionPane Demo");
Container contentPane = f.getContentPane();
JButton b = new JButton("Show Option Dialog");
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 OptionDialog();
}
public void actionPerformed(ActionEvent e) {
String title = "Option Dialog";
String message = "您喜欢吃汉堡吗?";
int messageType = JOptionPane.QUESTION_MESSAGE;
// 由于我们的optionType设置成JOptionPane.YES_NO_CANCEL_OPTION,因此对话框中会有三个按钮.我们在options
// 的String Arrray中设置这三个按钮的名称,并以options[1]按钮为默认值,若将options参数设为null,系统会原来
// 的按钮名称来显示.
int optionType = JOptionPane.YES_NO_CANCEL_OPTION;
String[] options = { "喜欢", "不喜欢", "取消" };
int result = JOptionPane.showOptionDialog(f, message, title,
optionType, messageType, null, options, options[1]);
if (result == JOptionPane.YES_OPTION)
label.setText("您选择:喜欢");
if (result == JOptionPane.NO_OPTION)
label.setText("您选择:不喜欢");
if (result == JOptionPane.CANCEL_OPTION)
label.setText("您选择:取消");
if (result == JOptionPane.CLOSED_OPTION)
label.setText("您没做任何选择,并关闭了对话框");
}
}
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();
}
}
}