Loop issues

I am reading data from a serial port inside a while loop like this:

while((len = this.getIn().read(buffer)) > 0) {
    data = new String(buffer, 0, len);
    System.out.println("data len " + len);
    handleModemresponse(data);
}

      

but when reading data from a stream, the main AWT window, which has a disconnect button, does not receive any listeners (the whole window does not receive listeners). It only listens when the transmission is complete, i.e. Outside the while loop.

I want my AWT window to listen for my actions when it is also in a while loop.

Any ideas how I can achieve this?

+1


a source to share


4 answers


Create a new thread for the read action.

public class LongProcess implements Runnable {
  public void startProcess() {
    Thread t = new Thread(this);
    t.start();
  }

      public void run() {
// Define inputstream here
        while((len = inputStream.read(buffer)) > 0) {
         data = new String(buffer, 0, len);
         System.out.println("data len " + len);
         handleModemresponse(data);
        }
      }
    }

      



EDIT (after Tom Hawtin's comment - tackline):

SwingUtilities.invokeLater(new LongProcess ());

      

+5


a source


It looks like you have everything in one thread - this way, while your working method is executing, your GUI appears to be blocked and doesn't respond to any action until the loop ends.



You need to separate your visit to the GUI in one thread and your work method in another.

+4


a source


The read method you are calling is blocking. You need to move it on a different thread to keep your listeners running.

+2


a source


I suspect that you should be pushing this while loop to a separate thread so as not to bind the AWT thread during transmission.

+1


a source







All Articles