不能在另一个类的swing组件中设置值 [英] cant set values in swing components in another class

查看:85
本文介绍了不能在另一个类的swing组件中设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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");
      }
}

我还有另一个将设置文本的类 textArea ,我将MyFrame扩展为访问另一个类中的textArea。

And I have this another class that will set the text of textArea , in wich I extended MyFrame to acces textArea in another class.

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

然后我实例化UpdateText并调用函数settext。但文字似乎并没有在GUI中出现。 请帮助

Then i instantiate UpdateText and call the function settext. but the text doesnt seem to apear in the GUI. please help

推荐答案

首先,不要覆盖 setText ()方法除非你想要不同的行为。其次,你不需要扩展任何东西。所有你需要做的就是按照这些简单的步骤进行设置!

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. 中UpdateText 类,将这些行放在其中:

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

MyFrame gui;

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


  • 在'MyFrame`类中,将此行放在开头:

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

    UpdateText ut = new UpdateText(this);
    


  • 现在,您可以参考来自 UpdateText 类的 MyFrame 类,前面是您想要更改的内容 gui 。例如,假设您要更改textarea的文本。代码如下:

    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!");
    

    快乐的编码! :)

    这篇关于不能在另一个类的swing组件中设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆