Question

I have a problem with setting text in JTextArea, I tried setText(which I'd prefer) and append also. I do not know where the problem is, I got client-server app. I want to put message that server sends in JTextField but I am unable to here is my code:

client side code which is reciving the message properly:

try
    {


        Socket socket = new Socket("localhost", PORT);
        BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
        DataOutputStream output = new DataOutputStream(socket.getOutputStream());
        BufferedReader serverInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        output.writeBytes(outputString + "\n");
        inputString = serverInput.readLine(); // private String inputString
        mymodel.setTextArea(inputString); // this is not working
        System.out.println(inputString); // this is working
        socket.close();

    }
    catch...

setTextArea method:

public void setTextArea(String string)
{
    MyPanel mypanel = new MyPanel();
    mypanel.textArea.setText(string); // debugger shows that the string contains message from server
}

I have set textarea to public since setter method weren't working, actually this one isn't working also. I do not know where the problem is, and debugger isn't helping me either.

Looking for your answers

EDIT:

JTextTable code:

textArea = new JTextArea(1, 30);
textArea.setEditable(false);
panel.add(textArea, c);
Was it helpful?

Solution 4

Try to get access through getter. Like

public JTextArea getTextArea()
{
     return jTextAreaField;
}

and then

getTextArea().append("ur text");

OTHER TIPS

You're creating a new instance of MyPanel each time the setTextArea method is called, this means that what ever is on the screen isn't been used to apply the text you are sending it.

Instead, you should use the original instance of MyPanel that you created to show on the screen...

It's also impossible to determine if you are calling the blocking I/O from the content of the Event Dispatching Thread or interacting with the UI from a different thread. In either case, it's highly unrecommended

Take a look at Concurrency in Swing for more details

There are two main problems:

  1. You perform the UI modification on the same thread as the IO, which you should never do. Consider working with SwingWorker for I/O operations.

  2. In setTextArea you are not accessing the instance of MyPanel that you already have, but creating a new one. So the changes are not done in the MyPanel instance that you already have...

   JTextArea t=new JTextArea();
   t.append("Text");
   no Method in java to set Text for JTextArea.
   the append method to add text in JTextArea
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top