java - Calling setEnable within an ActionListener -
in game making buttons, when click on "next" button, other buttons become 'grayed out' cannot click on them. have code in actionlistener 'next' button:
public class nextlistener implements actionlistener { public void actionperformed(actionevent e) { nextbutton.setenabled(false); callbutton.setenabled(false); raisebutton.setenabled(false); } }
however, when run program, buttons not gray out, , error:
exception in thread "awt-eventqueue-0" java.lang.nullpointerexception
why doesn't work?
you're trying call methods on null variables, suggests 1 or of jbutton variables you're calling setenabled(...)
on null. solution: assign valid references variables before trying call methods on them.
this can done via constructor parameter or such. or better yet, give class holds button variables public method allows change state of buttons, , pass reference of object, container object actionlistener.
e.g.,
import java.awt.event.actionlistener; import javax.swing.jbutton; public class mycontainer { jbutton nextbutton = new jbutton("next"); jbutton callbutton = new jbutton("call"); jbutton raisebutton = new jbutton("raise"); private actionlistener nextlistener = new nextlistener(this); public void buttonssetenabled(boolean enabled) { nextbutton.setenabled(enabled); callbutton.setenabled(enabled); raisebutton.setenabled(enabled); } }
elsewhere
public class nextlistener implements actionlistener { private mycontainer mycontainer; public nextlistener(mycontainer mycontainer) { this.mycontainer = mycontainer; } public void actionperformed(java.awt.event.actionevent e) { mycontainer.buttonssetenabled(false); }; }
Comments
Post a Comment