showInputDialog - 单击取消选项

问题描述

如果用户在 inputDialog 上单击取消,如何处理?我尝试过之前发布的解决方案,但都没有奏效。

这是我的代码

{{1}}

解决方法

试试这个:

String bidString;
while (true) {
    bidString = JOptionPane.showInputDialog(null,"Place your bid ","Bid",JOptionPane.PLAIN_MESSAGE);
    if (bidString == null) {
        System.out.println("cancelled");
        break;
    }
    if (bidString.isEmpty()) {
        System.out.println("wrong entry");
        JOptionPane.showMessageDialog(null,"You must enter a value","The Numbers Game",JOptionPane.ERROR_MESSAGE);
        continue;
    }else{
        try {
            int bid = Integer.parseInt(bidString);
        } catch (NumberFormatException nfe) {
            System.out.println("no number entered");
            continue;
        }
        break;
    }
}