简体   繁体   中英

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. 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 . I've tried some ways but none of them works:

  • change textAreaMessages; to private static JTextArea textAreaMessages; => My IDE (IntelliJ IDEA) yield an error when I run the program
  • 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.

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 :

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; and while calling handleInputStream () pass the instance of this class and call the setter to append the text.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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