java - Why can't this class find this array? -
i have array works in first class (coloredwordsexperiment), while sec class, (buttonhandler), cannot find it.
the unusual thing if i, in buttonhandler class, substitute coloredwords.labels[i] or let's "coloredwords.labels[1]" coloredwords.labels1, while in first class declare jlabel labels1 = new jlabel;
works.
that's had since have 12 labels decided utilize array instead. problem class buttonhandler cannot find variable "coloredwords.labels[i]".
this code (i left out unimportant stuff otherwise code quite long):
public class coloredwordsexperiment { buttonhandler buttonhandler; coloredwordsexperiment(){ jlabel[] labels = new jlabel[12]; (i = 0; < 12; i++) { labels[i] = new jlabel("press button"); labels[i].setpreferredsize(new dimension(90,40)); labels[i].setopaque(true); labels[i].setbackground(color.white); labels[i].sethorizontalalignment(swingconstants.center); labelcontainer.add(labels[i]); } button1 = new jbutton("matching"); buttonhandler = new buttonhandler(this); button1.addactionlistener(buttonhandler); } public static void main(string[] arg) { new coloredwordsexperiment(); } }
-
class buttonhandler implements actionlistener { coloredwordsexperiment coloredwords; public buttonhandler(coloredwordsexperiment coloredwords) { this.coloredwords = coloredwords; } @override public void actionperformed(actionevent e){ if (e.getactioncommand().equals("matching")) { (i = 0; < 12; i++) { coloredwords.labels[i].settext("text changed"); } } }
jlabel[] labels
variable declared within constructor of coloredwordsexperiment
class. move field in class , initialize in class constructor:
public class coloredwordsexperiment { buttonhandler buttonhandler; //it should declared here jlabel[] labels; coloredwordsexperiment() { //this variable within class constructor //jlabel[] labels = new jlabel[12]; //this line initializes labels field labels = new jlabel[12]; // rest of code... } }
also, should declare getter method obtain 1 of jlabel
s within labels
variable instead of using direct access variable. create code cleaner.
java arrays
No comments:
Post a Comment