java - How do you access/modify a JFrame object from a different class? -
i trying create code create text box inside of jframe object , after button clicked, text inside box change. still confused on how create text box , how edit inside other class. have tried far won't work due lack of ability access jframe separate class. have far.
import javax.swing.jbutton; import javax.swing.jpanel; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jtextarea; import java.awt.*; import java.awt.event.*; public class blackjackgui{ public static void main(string[] args){ jframe frame= new jframe("blackjack"); frame.setvisible(true); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setsize(400, 500); jpanel panel=new jpanel(); frame.add(panel); jbutton hit=new jbutton("hit"); panel.add(hit); hit.addactionlistener(new action()); //make text box } static class action extends blackjackgui implements actionlistener{ public void actionperformed (actionevent e){ //code edit text in text box } } }
- first , foremost: most of code out of static main method. jframe buried in main method making , child components inaccessible. goal have 2 objects interact, , require create well-behaved oop-compliant classes. -- create classes fields, such jtextarea field if need be, public accessor , mutator methods, constructors.
- yes need main method, purpose should create main actors, allow them connect somehow (say passing 1 parameter other), , setting program in motion. should little else.
- next , important: don't use inheritance purpose since inheritance not used allow 1 class communicate (at least not you're using it). example, having 2nd class inherit blackjackgui serve no useful purpose.
- instead composition key. have 1 class hold field of other type , assign correct viable reference, , voilĂ , you're set.
Comments
Post a Comment