Search code examples
javavalidationjoptionpane

Java - My JOptionPane does not close when cancel or 'x' is pressed


I have the following class (testDate) which tests another class (MyDate), when these 3 lines are executed, the inputDialog box doesn't close when I cancel or little 'x' top right.

myDay = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the day of the month, you're travelling on: "));
myMonth = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the month (1-12), you're travelling on: "));
myYear = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the year, you're travelling on: "));

Here is the full testDate Class:

import javax.swing.JOptionPane;

public class testDate {
public static void main(String[] args){
    int myDay = 0, myMonth = 0, myYear = 0; // initialising variables
    boolean dateCorrect = false;
    MyDate userTravelDate;

    do {
        try {
            do {
                myDay = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the day of the month, you're travelling on: "));
                myMonth = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the month (1-12), you're travelling on: "));
                myYear = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the year, you're travelling on: "));
                userTravelDate = new MyDate(myDay, myMonth, myYear);
            } while (userTravelDate.isDateValid(userTravelDate.formDate()) == false);
            dateCorrect = true;
        } 
        catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Please enter only integers!", "Error Occurred!", JOptionPane.ERROR_MESSAGE);
        }
    } while (dateCorrect == false);
    JOptionPane.showMessageDialog(null, myDay + "-" + myMonth + "-" + myYear);      
}

}

I would like to know if the input dialog boxes can be closed if I press 'X' or cancel, because at the moment if either 'x' or cancel are pressed it executes the line:

JOptionPane.showMessageDialog(null, "Please enter only integers!", "Error Occurred!", JOptionPane.ERROR_MESSAGE);

and keeps looping asking for day, month and year until these are right.


Solution

  • You could check the response of showInputDialog and break out of the loop in the absence of a response

    String response = JOptionPane.showInputDialog(...);
    if (response == null) {
       break; // X pressed!
    } else {
       myDay = Integer.parseInt(result);
       ...
    }