简体   繁体   English

Java GUI-如何通过静态方法将文本追加到JTextArea?

[英]Java GUI - How to append text to JTextArea from a static method?

I'm doing a simple exercise about client - server chat using Java IO. 我正在做一个关于客户端的简单练习-使用Java IO进行服务器聊天。 This is my code structure: 这是我的代码结构:

public class ChatRoomClientGUI{
    private JTextArea textAreaMessages;
    private JTextField textFieldMessage;
    private JButton buttonSendMsg;
    //...
    private static Socket socket = null;
    private static Scanner input = null;
    private static PrintWriter output = null;
    //...
    private static void handleInputStream(){
        String response = input.nextLine();
        textAreaMessages.append(response + "\n"); // Error here
    }
}

The problem I'm facing now is that I can't get access to the textAreaMessages variable because it is non-static and the handleInputStream() method is static . 我现在面临的问题是我无法访问textAreaMessages变量,因为它是非静态的 ,并且handleInputStream()方法是static的 I've tried some ways but none of them works: 我已经尝试了一些方法,但是没有一个起作用:

  • change textAreaMessages; 更改textAreaMessages; to private static JTextArea textAreaMessages; private static JTextArea textAreaMessages; => My IDE (IntelliJ IDEA) yield an error when I run the program =>运行程序时,我的IDE(IntelliJ IDEA)产生错误
  • change handleInputStream() to a non-static method => This didn't work either because I call this method from a static context and this can't be changed. handleInputStream()更改为非静态方法=>这也不起作用,因为我是从静态上下文调用此方法的,因此无法更改。

So any ideas how to fix this problem ? 那么有什么想法可以解决这个问题吗?

Thanks so much in advanced ! 非常感谢高级!

fairly ugly, but if you're sure there is going to be only one instance of your object, then modify (or add) the constructor to set a static variable to this : 相当难看,但如果你相信有将是你的对象只有一个实例,然后修改(或增加),以一个静态变量设置为构造this

private static ChatRoomClientGUI singleton;
...
public ChatRoomClientGUI() {
    singleton = this;
    ...
}

private static void handleInputStream(){
    String response = input.nextLine();
    singleton.textAreaMessages.append(response + "\n");
}

You can create getter and setter for private JTextArea textAreaMessages; 您可以为私有JTextArea textAreaMessages;创建getter和setter JTextArea textAreaMessages; and while calling handleInputStream () pass the instance of this class and call the setter to append the text. 并在调用handleInputStream ()时传递此类的实例并调用setter追加文本。

private static void handleInputStream(ChatRoomClientGUI gui) {
    String response = input.nextLine();
    gui.getTextField().append(response + "\n"); // Error here
}

public void setTextField(JTextField textField) {
    this.textAreaMessages = textField;
}

public JTextField getTextField() {
    return textAreaMessages;
}

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

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