我们之前曾经说过,JOptionPane也可以显示出Internal Dialog对话框,使用方法跟上面的范例一模一样,只是在方法名称上多 了Internal这个字眼,例如showInternalMessageDialog()等等,我们来看下面的范例:
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 InternalDialog implements ActionListener {
JInternalFrame internalFrame = null;
JLabel label = null;
public InternalDialog() {
JFrame f = new JFrame("OptionPane Demo");
Container contentPane = f.getContentPane();
JDesktopPane desktopPane = new JDesktopPane();
internalFrame = new JInternalFrame("Internal Frame", true, true, true,
true);
internalFrame.setLocation(20, 20);
internalFrame.setSize(200, 200);
internalFrame.setVisible(true);
Container icontentPane = internalFrame.getContentPane();
JButton b = new JButton("Show Internal Dialog");
b.addActionListener(this);
icontentPane.add(b, BorderLayout.CENTER);
label = new JLabel(" ", JLabel.CENTER);
icontentPane.add(label, BorderLayout.NORTH);
desktopPane.add(internalFrame);
contentPane.add(desktopPane, BorderLayout.CENTER);
f.setSize(350, 350);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
SwingUtil.setLookAndFeel();
new InternalDialog();
}
public void actionPerformed(ActionEvent e) {
String title = "Option Dialog";
String message = "您喜欢吃汉堡吗?";
int messageType = JOptionPane.QUESTION_MESSAGE;
int optionType = JOptionPane.YES_NO_CANCEL_OPTION;
String[] options = { "喜欢", "不喜欢", "取消" };
int result = JOptionPane.showInternalOptionDialog(internalFrame,
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();
}
}
}
读者在使用Internal Dialog时要特别注意,一般我们利用JOptionPane所产生的对话框均是modal为true状态,可是当你使用 Internal Dialog时对话框会变成modal为false状态.因此你可以不用关闭之前的对话框,就可以再按一次按钮,再产生一个Internal Dialog.你再运行上一例操作后就知道了. 若你想将JInternalFrame内的Internal Dialog model设为true,你可以有下面两种解决方法:
1.你可以建立JOptionPane对象,而非直接去调用JOptionPane的static方法来输出对话框.然后利用JOptionPane的createDialog()方 法,取得JDialog对象,再利用Dialog(JDialog继承Dialog)所提供的setModal()方法将modal设为true.
2.直接使用JDialog.