Search code examples
javaswingnullpointerexceptionjoptionpane

JOptionPane showInputDialog cancel button NullPointerException


I am trying unsuccessfully to trap the user into entering something for a filename. I'm just using input dialog because the path and extension are predetermined, and I need to append to the filename after the user enters it. As the title says I get NullPointerException any time the user clicks the cancel button. Since the input dialog has no way to remove the cancel button I've resorted to this method:

while (filename.equals(null) || filename.equals("")) {
    filename=JOptionPane.showInputDialog(this, "Please enter the filename.");
    if (filename.equals(null)) filename="";
}

I wouldn't generally have the filename.equals(null) in 2 places like that, but I tried both separately and out of frustration I tried together too. The NullPointerException still occurs on the line:

if (filename.equals(null)) filename="";

Is there any way to trap a cancel button (null) or prevent it?


Solution

  •   filename.equals(null) // Compare Object 
    

    Should be like

      filename == null // Compare Object references