Search code examples
javaswingjframechatjeditorpane

I can't acces the user's jEditorPane from another class


I'm doing a chat room with.I have one jFrame created with Netbeans but I have one problem. I have 2 important classes. One of them is the interface itself. Another one is a java class with run method that ckecks for new messages. I will start a thread that will run this run method. Every time I read a message, I want to use a method send of the interface. This method will append the message to JEditorPane. But it's not appending it. I do receive a message but it is not appearing in the jeditorpane... Could you help me, please?

This method is on ClientForm1( interface ). It will append a text to a editorpane. I start here a thread to check the incoming messages

public void send(String message){
    String messages;
    messages = jEditorPane1.getText();
    jEditorPane1.setText(messages+message+"\n");
}

And this is the run method for checking incoming messages from server. All the JFrame variables are private.

public ResMesClient(Socket socket, BufferedReader br, PrintStream p){
    this.socket = socket;
    is=br;
    ps = p;
}
@Override
@SuppressWarnings("empty-statement")
public void run(){
    String messages;
    try {
    //This thread will read the server messages
       ClientForm1 cf = new ClientForm1(socket,ps); //I create an object
       JFrame frame1 = cf;  //I create a frame and set it visible.
       frame1.setVisible(true);
    while(true){
        messages = is.readLine();
        System.out.println("From ResMesClient :  "+messages);
        if(!messages.equals("QUITCLIENT"));
        else cf.send("Set text works"); //I call a send method of ClientForm1 class
    }
   } catch (IOException ex) {
   }

These two are 2 different java classes in different files. But it is not appending... I tried a lot of things but it's not working... At least, I can tell for sure that I do receive a message, only it's not appending

Thank you in advance


Solution

  • Take care of calling SWT or Swing method from threads which not belong to the original Swing or SWT Thread -> Other Process or ThreadGroup.

    Using SWT it means calling the text.setText method must be executed using the Display object

    display.asyncExec(new Runnable() {
        public void run() {
           cf.send(message)
        }
    });
    

    using swing means

    SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            cf.send(message); 
         }
     });
    

    So your looü should look like this

    while(true){
        messages = is.readLine();
        System.out.println("From ResMesClient :  "+messages);
        if(!messages.equals("QUITCLIENT")) {
            SwingUtilities.invokeLater(new Runnable() {
               public void run() {
               cf.send(message); 
            }
        } else {
    
           //Quit programm or whatever
      }
    });
    }
    

    I think there should be your problem.