Search code examples
javaswinguser-interfacewhile-loopjtextarea

why does my textArea not work in real time?


I am trying to append a string I get from my client program. However I made it so that the append statement is in a while loop. Does this have an affect in not working in real time?

For areas like

   tfFIXMsg.append( inputLine + "\n\n\n");

and

       tfCSVLine.append(outputLine+"\n\n\n");

It will not show the message on the textArea UNTIL the while loop is done. How can I make it so that it will continue to recieve messages from client, and be able to output it onto the textArea in realtime

try {
    while ((inputLine = in.readLine()) != null) 
          { 
           System.out.println ("Server: " + inputLine); 


           tfFIXMsg.append( inputLine + "\n\n\n");


           int pos = inputLine.indexOf(inputLine, 0);
           h.addHighlight(50, 60, DefaultHighlighter.DefaultPainter);



           if (inputLine.trim().equals("Bye.")) {
               System.out.println("Exit program"); 
               break;
               } 

           Scanner input1 = new Scanner(new File(csvName));
           Scanner input2 = new Scanner(new File(csvName));
           Scanner input3 = new Scanner(new File(csvName));
           Scanner input4 = new Scanner(new File(csvName));


           String csvline = getCsvLineVal (getLocation34CSV(getTag34Value(Tag34Location(getTagCSV( parseFixMsg(inputLine ,inputLine))), getValueCSV( parseFixMsg(inputLine ,inputLine))), getVal34(input1,  input2)), getCSVLine( input3,  input4) );
           outputLine = compareClientFixCSV( getTagCSV( parseFixMsg(inputLine ,inputLine)), getValueCSV(parseFixMsg(inputLine ,inputLine)), getCSVTag(csvline), getCSVValue(csvline));

           out.println(outputLine);
           tfCSVLine.append(outputLine+"\n\n\n");

           input1.close();
           input2.close();
           input3.close();
           input4.close();



          }
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Solution

  • I guess, your code runs not on the EDT thread. If it runs, you should move that to the other one.

    Then, you can use from that other thread in order to update Swing UI elements:

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            tfFIXMsg.append( inputLine + "\n\n\n");
            // or whatever swing action you want to perform...
        }
    });
    

    If you need more sophisticated solutions try using SwingWorker class.