cant set values in swing components in another class

后端 未结 1 1939
半阙折子戏
半阙折子戏 2021-01-21 06:54

I have this class for my UI

public class MyFrame extends JFrame{
   JTextArea textArea;
  public MyFrame(){
   setSize(100,100);
   textArea = new JTextArea(50,         


        
1条回答
  •  鱼传尺愫
    2021-01-21 07:01

    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! :)

    0 讨论(0)
提交回复
热议问题