尝试使用输入对话框捕获阻止

时间:2011-11-19 02:52:50

标签: java input dialog try-catch

有没有办法让这段代码工作?我遇到的唯一问题是当用户点击取消时,会显示消息对话框。

public static void main(String[] args) {
    try {
        JOptionPane.showInputDialog("Enter something")
    } catch (Exception error) {
        JOptionPane.showMessageDialog("Something went wrong.");
    }
}

4 个答案:

答案 0 :(得分:2)

我修改了你的代码以便编译:

import javax.swing.JOptionPane;

public class Example {
public static void main(String[] args) {

    try {
        JOptionPane.showInputDialog("Enter something");
    } catch (Exception error) {
        error.printStackTrace();
        JOptionPane.showMessageDialog(null, "Something went wrong.");
    }
}

}

无论我是否点击“取消”或“确定”,它在运行时都能正常工作。没有例外。

我怀疑您的实际代码除了您发布的内容之外还有其他内容。

答案 1 :(得分:1)

当他们按下取消时,你会得到一个空值。我怀疑你得到了一个被抓住的NPE。检查null的返回值。

答案 2 :(得分:1)

import javax.swing.*;

class GetInput {

    public static void getInput() {
        String result = JOptionPane.showInputDialog(null, "Enter something");
        if (result==null) {
            System.out.println("User cancelled action.");
        } else {
            System.out.println("User entered '" + result + "'.");
        }
    }

    public static void main (String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                getInput();
                getInput();
            }
        });
    }
}

典型输出

User entered 'this code runs!'.
User cancelled action.
Press any key to continue . . .

答案 3 :(得分:-1)

try{
    //some code ;)                 
} catch(Exception e) {
    System.out.println(e.getMessage());
    JOptionPane.showMessageDialog(this, " erreur !!! :" + e.getMessage());   
}
相关问题