java - Private variable cannot reference to another method in the same class -
im new java , today have problem code when trying actionlistener java class here:
public class exam{ private void createform(){ ... jbutton jbtn = new jbutton("ok"); jbtn.addactionlistener((actionlistener) this); ... } public static void main(string[] args){ exam ex = new exam(); ex.createform(); } public void actionperformed(actionevent ae){ //ide show no variable name "jbtn" if (ae.getsource() == jbtn){ ... } } }
your jbtn
variable declared within createform
method. java uses called "scoping rules" make sure don't accidentally use variables don't mean to. declaring jbtn
in createform
, telling java compiler want use in method, , else. called "local" variable (as in, local method).
you want use "member variable" (it member of class). declared inside class, outside of method. in case, looks this:
public class exam{ jbutton jbtn; private void createform(){ ... jbtn = new jbutton("ok"); jbtn.addactionlistener((actionlistener) this); ... }
the declaration of variable @ class level, , in createform
being referenced in same way in actionperformed
.
this basic concept in java, might want take @ java tutorials go on ground. official tutorial place start.
Comments
Post a Comment