java - Changing text on a JLabel from another class -
so, have been trying figure out little bit , cannot figure out how it. want 1 of buttons in class change text of jlabel in gui class.
here code gui class:`import java.awt.container;
import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jtextfield; public class gui extends jframe{ container pane = getcontentpane(); jbutton guess = new jbutton("guess"); jbutton gen = new jbutton("generate number"); jtextfield userinput = new jtextfield(); jlabel numbers = new jlabel("press generate start."); jlabel guessednum = new jlabel(""); jlabel error = new jlabel(""); public void creategui(){ final int width = 325; final int height = 200; final int centerwidth = width / 4; final int centerheight = height / 4; guesshandler guesshandle; genhandler genhandle; pane.setlayout(null); guesshandle = new guesshandler(); guess.addactionlistener(guesshandle); genhandle = new genhandler(); gen.addactionlistener(genhandle); userinput.setbounds(centerwidth - 20, centerheight, 200, 20); guess.setbounds(userinput.getx() - 35, (userinput.gety() + 25), 105, 50); gen.setbounds((guess.getx() + 105), guess.gety(), 165, 50); error.setbounds(70, 125, 300, 20); numbers.setbounds(90, 0, 300, 20); guessednum.setbounds(20, 25, 300, 20); pane.add(userinput); pane.add(guess); pane.add(gen); pane.add(numbers); pane.add(guessednum); pane.add(error); setsize(width,height); settitle("number guesser"); setdefaultcloseoperation(exit_on_close); setvisible(true); setresizable(false); setlocation(350, 150); } }
and here code button trying change jlabel "error": `
import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jbutton; import javax.swing.jlabel; import javax.swing.jtextfield; public class guesshandler implements actionlistener{ public void actionperformed(actionevent e) { gui gui = new gui(); gui.changepos(4, 50, 0, 300, 20); gui.error.settext("hi guesshandler.java"); } }
first, add getter public
access second class can access field. like,
public jlabel geterror() { return error; }
or (as @madprogrammer suggested in comments, mutator) like
public void seterror(string txt) { error.settext(txt); }
then modify second class, , pass instance of gui
in constructor. like,
public class guesshandler implements actionlistener{ private gui gui; public guesshandler(gui gui) { this.gui = gui; } public void actionperformed(actionevent e) { gui.changepos(4, 50, 0, 300, 20); gui.seterror("hi guesshandler.java"); } }
Comments
Post a Comment