我有一个关闭我的应用程序(windowClosing()
)时显示的选项窗格。
我可以选择退出,最小化或取消。
如何在不关闭整个应用程序的情况下选择“取消”时关闭选项窗格?
Object[]options = {"Minimize", "Exit","Cancel"};
int selection = JOptionPane.showOptionDialog(
null, "Please select option", "Options", 0,
JOptionPane.INFORMATION_MESSAGE, null, options, options[1]);
System.out.println(selection);
switch(selection)
{
case 2:
{
// do something
}
}
答案 0 :(得分:3)
如果用户选择“取消”,您可以在yourFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
方法中拨打windowClosing()
....
答案 1 :(得分:2)
If (selection == JOptionPane.CANCEL_OPTION)
{
// DO your stuff related to cancel click event.
}
答案 2 :(得分:1)
Oracle documentation提供了一些提示:
final JDialog dialog = new JDialog(frame,
"Click a button",
true);
dialog.setContentPane(optionPane);
dialog.setDefaultCloseOperation(
JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
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)
&& (prop.equals(JOptionPane.VALUE_PROPERTY))) {
//If you were going to check something
//before closing the window, you'd do
//it here.
dialog.setVisible(false);
}
}
});
dialog.pack();
dialog.setVisible(true);
int value = ((Integer)optionPane.getValue()).intValue();
if (value == JOptionPane.YES_OPTION) {
setLabel("Good.");
} else if (value == JOptionPane.NO_OPTION) {
setLabel("Try using the window decorations "
+ "to close the non-auto-closing dialog. "
+ "You can't!");
}
您必须删除默认关闭操作并添加自己的侦听器,然后使用setVisible(false)
关闭它。