Can't set values ​​in swing components in another class

I have this class for my UI

public class MyFrame extends JFrame{
   JTextArea textArea;
  public MyFrame(){
   setSize(100,100);
   textArea = new JTextArea(50,50);
   Container content = getContentPane(); 
   content.add(textArea);
  }
 public static void main(String[] args){
          JFrame frame = new MyFrame();  
          frame.show();
          UpdateText u = new UpdateText();
          u.settext("Helloworld");
      }
}

      

And I have this other class that will set the text textArea

in which I have expanded MyFrame to acces textArea in another class.

public class UpdateText extends MyFrame{
    public void settext(String msg){
     textArea.setText(msg);
    }
}

      

Then I create UpdateText and call the settext function. but the text doesn't seem to show up in the GUI. please, help

+3


source to share


1 answer


First of all, don't override a method setText()

unless you want different behavior. Second, you have nothing to expand. All you have to do is follow these simple steps and you will be set!

  • In the class, UpdateText

    put these lines somewhere in it:

    MyFrame gui;
    
    public UpdateText(MyFrame in) {
        gui = in;
    }
    
          

  • In the "MyFrame" class, put this line at the beginning:

    UpdateText ut = new UpdateText(this);
    
          

You can now refer to everything in the class MyFrame

from within the class UpdateText

, navigating to what you want to change with gui

. For example, say that you want to change the text of your text box. The code will look like this:



gui.textArea.setText("Works!");

      

Happy coding! :)

+2


source







All Articles