Reputation: 9043
I have an option pane that is displayed upon closing my Application (windowClosing()
).
I have the options to exit, minimize or cancel.
How can I close the option pane on selecting 'cancel' without closing the entire application?
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
}
}
Upvotes: 1
Views: 337
Reputation: 20065
The Oracle documentation gives a tips :
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!");
}
You have to remove default close operation and add your own listener, then use setVisible(false)
to close it.
Upvotes: 1
Reputation: 24626
If (selection == JOptionPane.CANCEL_OPTION)
{
// DO your stuff related to cancel click event.
}
Upvotes: 2
Reputation: 8101
You can call yourFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
inside your windowClosing()
method, if user chooses "cancel"....
Upvotes: 3