Search code examples
javaswingclient-serverjtextareasettext

java GUI setText and append doesn't work from another class


I have just started looking at client and servers and I am linking a client to a gui, so far I have made it so when you enter text in the JTextField (called "Input") it sends it to Client.java and is printed out to make sure it works. How ever when I set something to be sent back and appended onto a JTextArea (called "Output") it is sent across and can be printed out but it is not set to the JTextArea. I have also tried using setText and that doesn't work either.

When I run Client.java it starts and in the cmd it says

sent

then in the cmd for the ClientGUI.java it says

it worked.

which is what was meant to be sent to the gui not the cmd.

How can I make it append text to the JTextArea from class Client?

FULL Code:

ClientGUI.java:

private void InputActionPerformed(java.awt.event.ActionEvent evt) {
    String input = Input.getText();
    Client c = new Client();
    c.input(input);
}                                     

public void output() {
    Output.append("it worked.");
    //Output.append(null);
}

Client.java:

public void input(String input) {
    System.out.println(input);
}

public void startUP() {
    System.out.println("sent");
    ClientGUI cg = new ClientGUI();
}

public static void main(String args[]) {          
    Client c = new Client();
    c.startUP();
    new ClientGUI().setVisible(true);

    try {
        Socket skt = new Socket("localhost", 1234);
        BufferedReader in = new BufferedReader(new
            InputStreamReader(skt.getInputStream()));
        System.out.print("Received string: '");

        while (!in.ready()) {}
        String output = in.readLine();
        System.out.println(output); // Read one line and output it

        System.out.print("'\n");
        in.close();
    }
    catch(Exception e) {
        System.out.print("Whoops! It didn't work!\n");
    }
}

Solution

  • Within main method instead of :

    new ClientGUI().setVisible(true);
    

    use:

    ClientGUI cgui = new ClientGUI();
    cgui.setVisible(true);
    

    Change :

    c.startUP();
    

    To

    c.startUP(cgui);
    

    And change startUP method of Client.java as follows:

        public void startUP(final ClientGUI cg){
           new java.util.Timer().schedule( 
            new java.util.TimerTask() {
                @Override
                public void run() 
                {
                     System.out.println("sent");
                     cg.output();
                }
            }, 
            5000 
    );