这是RequestAngentName类
public class RequestAgentName{
// instance variable daclaration
private static String uName;
/*
recursive method set username to instance variable
*/
public void setUserName(String name) throws NullPointerException
{
name = JOptionPane.showInputDialog(null, "Insert First Name and Last Initial", "Agent Name",
JOptionPane.PLAIN_MESSAGE);
// if user input is not empty
(line 24)if(!name.isEmpty())
{
// verify input is acceptable, if yes assign input to global variable
if(JOptionPane.showConfirmDialog(null, "Is This Your Name?\n\n " + name, "WARNING" , JOptionPane.YES_NO_OPTION) == JOptionPane.YES_NO_OPTION)
{
uName = name;
} // end if
// if input is not acceptable prompt user to reenter name
else
// if username is wrong reenter until correct
this.setUserName(name);
} // end if
// if input is empty prompt user to reenter
else
this.setUserName(name);
} //end method set username
// method to return user input
public String getUserName(){
return uName;
} // end method get username
} // end of Request name class
这是我在main中调用它的方式,我觉得可能是错误的地方
RequestAgentName userName = new RequestAgentName();
try {
(line 52) userName.setUserName(userName.getUserName());
new FNAFrame();
(new Thread(new FnaComponents())).start();
}
catch (NullPointerException npe){
npe.printStackTrace();
}
错误如下;
java.lang.NullPointerException
at fna.comments.generator.RequestAgentName.setUserName(RequestAgentName.java:24)
at fna.comments.generator.FNAFrame$1.run(FNAFrame.java:52)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:749)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:702)
at java.awt.EventQueue$3.run(EventQueue.java:696)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:719)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
建立成功(总时间:6秒)
答案 0 :(得分:0)
当你这样做时
name = JOptionPane(...);
当用户按下取消时,JOptionPane返回null
。因此,名称为null
。
因此
if(!name.isEmpty())
成为
if(!null.isEmpty())
您无法在null
上调用方法。因此抛出了NullPointerException
。一个简单的解决方案是:
if(name!=null && !name.isEmpty())
修改强>
我的不好,我没有看到对整个代码的影响。最好像这样解决它:
if (name == null){
// User hit cancel, so simply return/terminate
return;
} else if (!name.isEmpty()) {
// User pressed OK with a value
} else
// User pressed OK without value