3

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 another class that will set the text of textArea, in which I extended MyFrame to access textArea in another class.

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

Then I instantiate UpdateText and call the function settext. but the text doesn't seem to appear in the GUI.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Jude Calimbas
  • 2,764
  • 2
  • 27
  • 24
  • How is the textArea passed to UpdateText class? Are you sure they are the same textArea instance? – evanwong Apr 09 '12 at 17:35
  • @evanwong UpdateText extends MyFrame so it can have the textArea – Jude Calimbas Apr 09 '12 at 17:40
  • 1
    ... except this is clearly wrong: textArea = JTextArea(50,50); – ControlAltDel Apr 09 '12 at 17:42
  • 1
    1) See See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/a/9554657/418556) 2) Don't extend frame unless implementing new functionality. 3) Take out `setSize(100,100);` and call `pack()` at the end of the constructor. (Adjust the size of the GUI by adjusting the args passed to the text area constructor.) – Andrew Thompson Apr 09 '12 at 17:43

1 Answers1

2

First of all, don't override the setText() method unless you want different behavior. Second of all, you don't have to extend anything. All you have to do is follow these simple steps and you'll be set!

  1. In the UpdateText class, put these lines somewhere in it:

    MyFrame gui;
    
    public UpdateText(MyFrame in) {
        gui = in;
    }
    
  2. In the 'MyFrame` class, put this line at the beginning:

    UpdateText ut = new UpdateText(this);
    

Now, you can refer to everything in the MyFrame class from the UpdateText class by preceeding what you want to change with gui. For example, say you wanted to change the text of your textarea. The code would be the following:

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

Happy coding! :)

fireshadow52
  • 6,298
  • 2
  • 30
  • 46