java - setCharAt a for JLabel -
i'm trying replace setcharat can used jlabel... i've been on oracle doc's looking solution. don't know if i'm looking wrong thing or doesn't exists.. if doesn't exists how work around that? understand naming convention off , changing them possible...
import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.util.arraylist; import java.util.arrays; import java.util.collections; import javax.swing.*; public class hangmanpanel extends jpanel { static boolean found; private static final long serialversionuid = -5793357804828609325l; public static string answerkey() { //get random array element string array[] = new string[10]; array[0] = "hamlet"; array[1] = "mysts of avalon"; array[2] = "the iliad"; array[3] = "tales edger allan poe"; array[4] = "the children of hurin"; array[5] = "the red b" + "+adge of courage"; array[6] = "of mice , men"; array[7] = "utopia"; array[8] = "chariots of gods"; array[9] = "a brief history of time"; arraylist<string> list = new arraylist<string>(arrays.aslist(array)); collections.shuffle(list); string s = list.get(0); return s; } public stringbuilder dashreplace(string s) { //replace non-white space char dashes , creates stringbuilder object string tw = s.replaceall("\\s", "-"); system.out.print(tw + "\n"); stringbuilder answerkey = new stringbuilder(tw); return answerkey; } public static int findandreplace(string s, jlabel answerkey, string sc, char ch) { //find position of user input , replace int pos = -1; found = false; while(true){ pos = s.indexof(sc, pos+1); if(pos < 0){ break; }else{ found = true; //setcharat dosen't work jlable answerkey.setcharat(pos, ch); } } jlabel answerkey2 = new jlabel(answerkey.tostring()); return pos; } public hangmanpanel(final string s){ this.setlayout(null); jlabel heading = new jlabel("welcome hangman app"); jbutton button = new jbutton("ok"); //get input jlabel tflable = new jlabel("please enter letter:"); final jlabel answerkey = new jlabel(dashreplace(answerkey()).tostring()); final jtextfield text = new jtextfield(10); heading.setsize(200, 50); tflable.setsize(150, 50); text.setsize(50, 30); button.setsize(60, 20); answerkey.setsize(200, 100); heading.setlocation(300, 10); tflable.setlocation(50, 40); text.setlocation(50, 80); button.setlocation(100, 85); answerkey.setlocation(100,85); this.add(heading); this.add(tflable); this.add(text); this.add(button); this.add(answerkey); button.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { // can't access text string sc = text.gettext(); char ch = sc.charat(0); findandreplace(s, answerkey, sc, ch); } }); } }
the method available setting text jlabel components settext. strings immutable. therefore, can use stringbuilder:
stringbuilder builder = new stringbuilder(answerkey.gettext()); builder.setcharat(pos, ch); answerkey.settext(builder.tostring());
Comments
Post a Comment