| Author |
JOptionPane
|
Maureen Charlton
Ranch Hand
Joined: Oct 04, 2004
Posts: 218
|
|
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
Joined: Aug 20, 2001
Posts: 1815
|
|
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.
|
Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
|
 |
Maureen Charlton
Ranch Hand
Joined: Oct 04, 2004
Posts: 218
|
|
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
Joined: Aug 11, 2004
Posts: 9
|
|
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 ]
|
 |
 |
|
|
subject: JOptionPane
|
|
|