Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JOptionPane

 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When using JOptionPane to get input from a user and you wish to write code to do something i.e. Println ("Program finished") when the user selects the Cancel button. What would you write?

Would you write:
dataInput = JOptionPane.showInputDialog(message1);
OK = dataInput.equals(null);

if (OK)
{
System.out.println("Cancel has been selected. Data Input finished.");
}//end if statement

When I did this I got an error Null Pointer Exception and I don't know why?
Could someone confirm whether using null as the validation criteria for the Cancel button being selected is alright? Or is there a better way of doing this?
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
don't use dataInput.equals(null), use dataInput == null.

The former assumes that the dataInput actually refers to an object and thus can call a method on that object. The latter checks to see if the reference is to an object or to null.
 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joel,

Thank you! It worked BUT I would like to understand a little more.

You use equals when it is an object; in other words, a creation of the class (the constructor using the new word) - it that the only time you use equals?
 
Dave Cryder
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maureen,

Yes. You can't reference .equals() on a reference that isn't actually referencing an object of the class.



You should check the state of the object by using "==" if there is a chance that the object wasn't initialized.

[ edited to break long line -ds ]
[ December 03, 2004: Message edited by: Dirk Schreckmann ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic