简体   繁体   English

如何从一个类到另一个类访问JTextArea

[英]How to access JTextArea from a class to another class

I want to access status so I can append values to it but my code doesn't seem to work. 我想访问状态,以便可以向其附加值,但是我的代码似乎不起作用。 Please help me. 请帮我。

public class NewClient extends JFrame implements ActionListener{


private static final int WIDTH = 600;
private static final int HEIGHT = 400;
public static JTextArea chat, event, cwindow, c2window, type, status;

public NewClient(){

    status = new JTextArea(30,10);
    status.setEditable(false);
}

Here's the other class 这是另一堂课

public class NewServer{


public static NewClient client;

public static void main(String args[]){
       client.status.append("Online");
}

There two things to note here: 这里有两件事要注意:

You have to create object to invoke its constructor, otherwise you will hit NullPointerException in the following line 您必须创建对象以调用其构造函数,否则将在下一行中命中NullPointerException

client.status.append("Online");

So, the fix is to create an object and assign value: 因此,解决方法是创建一个对象并分配值:

client = new NewClient();
client.status.append("Online");

Static variables like status need not be invoked through object. 诸如status类的静态变量无需通过对象调用。 So, instead of assigning value like the following: 因此,不要像下面那样分配值:

client.status.append("Online");

You can directly invoke the variable using class name: 您可以使用类名直接调用变量:

client = new NewClient();   
NewClient.status.append("Online");

If you note above, we created new object for NewClient so that the value for status text area is initialized as part of NewClient 's constructor. 如果在上面注意到,我们为NewClient创建了新对象,以便将status文本区域的值初始化为NewClient构造函数的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM