0

我有以下类(testDate),它测试另一个类(MyDate),当执行这3行时,当我取消或右上角的小“x”时输入对话框不会关闭。

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: "));

这是完整的 testDate 类:

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);      
}

}

我想知道如果我按下“X”或取消输入对话框是否可以关闭,因为此时如果按下“x”或取消,它会执行以下行:

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

并不断循环询问日、月和年,直到这些都是正确的。

4

1 回答 1

2

您可以在没有响应的情况下检查循环的响应showInputDialogbreak循环外的响应

String response = JOptionPane.showInputDialog(...);
if (response == null) {
   break; // X pressed!
} else {
   myDay = Integer.parseInt(result);
   ...
}
于 2013-03-27T15:49:50.490 回答