tags:

views:

255

answers:

4

I'm reading data from serial port inside while loop as follows:

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

but, while reading the data from stream starts, the main AWT window, which has a disconnect button, is not getting any listeners (whole window not getting listeners). It only listens when transfer completes, i.e., outside while loop.

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

Any ideas how I can achieve this?

+1  A: 

I suspect you should be pushing this while loop into a separate thread so as to not tie up your AWT thread during the transfer.

paxdiablo
@Pax: Sorry for the formatting which erased your formatting ;) You did a much better job at rephrasing this question.
VonC
No probs, @VonC, that often happens, mainly because I'm anal retentive about making the question look good once I start editing, and I take too long.
paxdiablo
+4  A: 

It looks like you have everything in one thread - thus while your working method is in progress, your GUI seems blocked and does not respond to any actions until the loop ends.

You have to separate your GUI attendance in one thread and your working method in another.

Martin Lazar
+2  A: 

The read method you are calling is blocking. You need to move it in a different thread in order for your listeners to keep working.

kgiannakakis
To be more accurate, blocking I/O isn't the issue here. It's the long-running process on GUI thread that is creating the trouble.
Tahir Akhtar
+5  A: 

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 comment Tom Hawtin - tackline):

SwingUtilities.invokeLater(new LongProcess ());
Markus Lausberg
java.awt.EventQueue.invokeLater to get back into the AWT EDT thread.
Tom Hawtin - tackline
er...invokeLater is for notifiying the gui when the thread is finshed:finally in run() do something like....ies.invokeLater( new Runnable() { ...public void run() { gui.taskIsDone( result );....
KarlP