Java - 当取消或按下'x'时,我的JOptionPane不会关闭

时间:2013-03-27 15:44:53

标签: java validation joptionpane

我有下面的类(testDate)来测试另一个类(MyDate),当执行这3行时,inputDialog框在我取消时没有关闭,或者在右上角没有'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);

并继续循环询问日期,月份和年份,直到这些是正确的。

1 个答案:

答案 0 :(得分:2)

在没有回复的情况下,您可以检查showInputDialogbreak的回复

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