I had created a JOptionPane
of type showInputDialog
. When it opens it, it shows me two buttons: OK and Cancel. I would like to handle the action when I push on Cancel button, but I don't know how to reach it. How can I get it?
Check the code below: JOptionPane pane = new JOptionPane("message"); JDialog dialog = pane. createDialog(null, "Title"); dialog. setDefaultCloseOperation(WindowConstants.
If the user clicks "cancel", the response will be null. If they click "ok" without entering any text the response will be the empty string.
JOptionPane closing coderanch.com If it's really safe to just kill all JOptionPanes you can do something like this: public static void main(String[] args) { new Thread() { public void run() { for (int i = 0; i < 3; i++) { try { Thread. sleep(2000); } catch (InterruptedException e) { } JOptionPane.
Passing null to it just indicates that there's not an associated "parent" dialog - ie, the dialog being displayed does not belong to another dialog. Instead, you can use the overloaded signature and call it like this: showInputDialog(Object message)
For example:
int n = JOptionPane.showConfirmDialog(
frame, "Would you like green eggs and ham?",
"An Inane Question",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
} else if (n == JOptionPane.NO_OPTION) {
} else {
}
Alternatively with showOptionDialog
:
Object[] options = {"Yes, please", "No way!"};
int n = JOptionPane.showOptionDialog(frame,
"Would you like green eggs and ham?",
"A Silly Question",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (n == JOptionPane.YES_OPTION) {
} else if (n == JOptionPane.NO_OPTION) {
} else {
}
See How to Make Dialogs for more details.
EDIT: showInputDialog
String response = JOptionPane.showInputDialog(owner, "Input:", "");
if ((response != null) && (response.length() > 0)) {
}
This is an old question, and I am an Java newbie so there might be better solutions, but I wanted to know the same, and maybe it can help others, what I did was to check if the response was null.
If the user clicks "cancel", the response will be null. If they click "ok" without entering any text the response will be the empty string.
This worked for me:
//inputdialog
JOptionPane inpOption = new JOptionPane();
//Shows a inputdialog
String strDialogResponse = inpOption.showInputDialog("Enter a number: ");
//if OK is pushed then (if not strDialogResponse is null)
if (strDialogResponse != null){
(Code to do something if the user push OK)
}
//If cancel button is pressed
else{
(Code to do something if the user push Cancel)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With