Currently having an issue where I am popping a message dialog up to prompt the user to enter a string. I have a check for the name being empty which works properly if they hit the "ok" button however if the user hits the cancel button (whether they input anything into the textbox or not) then I get the following error:
java.lang.NullPointerException
at cc.nisc.mapping.mappingadvsearch.ResultsPopupMenu$1.doActionPerformed(ResultsPopupMenu.java:98)
at cc.nisc.gui.action.NiscAction.actionPerformed(NiscAction.java:225)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)
The relevant code is :
public final ResultsMenuAction createLayerAction = new ResultsMenuAction("uiCreateLayer") {
@Override
protected void doActionPerformed(ActionEvent e) {
try {
String queryName = JOptionPane.showInputDialog(WinMgr.getInstance().getSelectedNavigator(),
"Enter a name for your exported query layer",
"Enter Query Name",
JOptionPane.QUESTION_MESSAGE);
if (queryName.isEmpty()) {
JOptionPane.showMessageDialog(WinMgr.getInstance().getSelectedNavigator(),
"Please enter a name for your query",
"Empty name",
JOptionPane.WARNING_MESSAGE);
return;
}
....
....
How can I check to see if the cancel button has been clicked in order to return instead of raising the error?
From the JavaDoc on JOptionPane.showInternalInputDialog()
which is called by the method you're using:
Returns: user's input, or null meaning the user canceled the input
Thus null
would indicate the input being cancelled.
To check for null or empty input, you'd first check the for null and then for empty, since calling isEmpty()
on null will result in an NPE.
Keep in mind that ||
is the short circuit or operator, i.e. it will evaluate expressions from left to right and stop whenever a condition becomes true. Thus if( queryName == null || queryName.isEmpty() )
won't throw a NPE because if queryName
is null the condition is true and isEmpty()
is never called.
In contrast a single pipe |
isn't a short circuit operator, i.e. both expressions are evaluated regardless of whether the left is already true. Thus queryName == null | queryName.isEmpty()
might still throw a NPE.