How do you monitor a background thread and update the GUI

Hello,
I have a thread which makes its output available on PipedInputStreams. I should like to have other threads monitor the input streams and update a JTextArea embedded in a JScrollPane using the append() method.
According to the Swing tutorial, the JTextArea must be updated on the Event Dispatch Thread. When I use SwingUtilities.invokeLater () to run my monitor threads, the component is not redrawn until the thread exits, so you don't see the progression. If I add a paint () method, the output is choppy and the scrollbar doesn't appear until the thread exits.
Ironically, if I create and start new threads instead of using invokeLater(), I get the desired result.
What is the correct architecture to accomplish my goal without violating Swing rules?
Thanks,
Brad
Code follows:
import java.lang.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
public class SystemCommand implements Runnable
     private String[] command;
     private PipedOutputStream pipeout;
     private PipedOutputStream pipeerr;
     public SystemCommand ( String[] cmd )
          command = cmd;
          pipeout = null;
          pipeerr = null;
     public void run ()
          exec ();
     public void exec ()
          // --- Local class to redirect the process input stream to a piped output stream
          class OutputMonitor implements Runnable
               InputStream is;
               PipedOutputStream pout;
               public OutputMonitor ( InputStream i, PipedOutputStream p )
                    is = i;
                    pout = p;
               public void run ()
                    try
                         int inputChar;
                         for ( ;; )
                              inputChar = is.read();
                              if ( inputChar == -1 ) { break; }
                              if ( pout == null )
                                   System.out.write ( inputChar );
                              else
                                   pout.write ( inputChar );
                         if ( pout != null )
                              pout.flush ();
                              pout.close ();
                         else
                              System.out.flush();
                    catch ( Exception e ) { e.printStackTrace (); }     
          try
               Runtime r = Runtime.getRuntime ();
               Process p = r.exec ( command );
               OutputMonitor out = new OutputMonitor ( p.getInputStream (), pipeout );
               OutputMonitor err = new OutputMonitor ( p.getErrorStream (), pipeerr );
               Thread t1 = new Thread ( out );
               Thread t2 = new Thread ( err );
               t1.start ();
               t2.start ();
               //p.waitFor ();
          catch ( Exception e ) { e.printStackTrace (); }
     public PipedInputStream getInputStream () throws IOException
          pipeout = new PipedOutputStream ();
          return new PipedInputStream ( pipeout );
     public PipedInputStream getErrorStream () throws IOException
          pipeerr = new PipedOutputStream ();
          return new PipedInputStream ( pipeerr );
     public void execInThread ()
          Thread t = new Thread ( this );
          t.start ();
     public static JPanel getContentPane ( JTextArea ta )
          JPanel p = new JPanel ( new BorderLayout () );
          JPanel bottom = new JPanel ( new FlowLayout () );
          JButton button = new JButton ( "Exit" );
          button.addActionListener ( new ActionListener ( )
                                   public void actionPerformed ( ActionEvent e )
                                        System.exit ( 0 );
          bottom.add ( button );
          p.add ( new JScrollPane ( ta ), BorderLayout.CENTER );
          p.add ( bottom, BorderLayout.SOUTH );
          p.setPreferredSize ( new Dimension ( 640,480 ) );
          return p;
     public static void main ( String[] argv )
          // --- Local class to run on the event dispatch thread to update the Swing GUI
          class GuiUpdate implements Runnable
               private PipedInputStream pin;
               private PipedInputStream perr;
               private JTextArea outputArea;
               GuiUpdate ( JTextArea textArea, PipedInputStream in )
                    pin = in;
                    outputArea = textArea;
               public void run ()
                    try
                         // --- Reads whole file before displaying...takes too long
                         //outputArea.read ( new InputStreamReader ( pin ), null );
                         BufferedReader r = new BufferedReader ( new InputStreamReader ( pin ) );
                         String line;
                         for ( ;; )
                              line = r.readLine ();
                              if ( line == null ) { break; }
                              outputArea.append ( line + "\n" );
                              // outputArea.paint ( outputArea.getGraphics());
                    catch ( Exception e ) { e.printStackTrace (); }
          // --- Create and realize the GUI
          JFrame f = new JFrame ( "Output Capture" );
          f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
          JTextArea textOutput = new JTextArea ();
          f.getContentPane().add ( getContentPane ( textOutput ) );
          f.pack();
          f.show ();
          // --- Start the command and capture the output in the scrollable text area
          try
               // --- Create the command and setup the pipes
               SystemCommand s = new SystemCommand ( argv );
               PipedInputStream stdout_pipe = s.getInputStream ();
               PipedInputStream stderr_pipe = s.getErrorStream ();
               // --- Launch
               s.execInThread ( );
               //s.exec ();
               // --- Watch the results
               SwingUtilities.invokeLater ( new GuiUpdate ( textOutput, stdout_pipe ) );
               SwingUtilities.invokeLater ( new GuiUpdate ( textOutput, stderr_pipe ) );
               //Thread t1 = new Thread ( new GuiUpdate ( textOutput, stdout_pipe ) );
               //Thread t2 = new Thread ( new GuiUpdate ( textOutput, stderr_pipe ) );
               //t1.start ();
               //t2.start ();
          catch ( Exception e ) { e.printStackTrace (); }
          

Thanks for pointing out the SwingWorker class. I didn't use it directly, but the documentation gave me some ideas that helped.
Instead of using invokeLater on the long-running pipe-reader object, I run it on a normal thread and let it consume the output from the background thread that is running the system command. Inside the reader thread I create a tiny Runnable object for each line that is read from the pipe, and queue that object with invokeLater (), then yield() the reader thread.
Seems like a lot of runnable objects, but it works ok.

Similar Messages

  • In making a monthly budget how do you repeat for next month and update the dates to the next month?

    i want to make my budget speadsheet update the month and date as it goes to the next month automatically, from sheet to sheet.  is there any way to make this happen?

    You could have a cell where you enter the month and year...
    Or you could pull the month and year from the first entry in the date column.  Like Barry I would want more information regarding your  set up before proposing any other, more specific, ideas.

  • How do you move a single album, and not the whole library, in iPhoto to an external hard drive?

    How do you move a single album, and not the whole library, in iPhoto to an external hard drive?

    File -> Export to a folder and copy it over.
    That will give you a folder with the images. There is no way to move an album outside of iPhoto. You would need to have a library containing it.
    Regards
    TD

  • How do you print an email attachment and not the email itself. please.

    how do you print an email attachment and not the email itself.  please.
    This question was solved.
    View Solution.

    Hi there, if there is text in the body of the email it will print automatically when sent to an ePrint email address. The only way to just have the attachment print is for there to be no text in the email body.
    Hope that helps answer your question.
    If my reply helped you, feel free to click on the Kudos button (hover over the "thumbs up").
    If my reply solved your problem please click on the Accepted Solution button so other Forum users may benefit from viewing the post.
    I am an HP employee.

  • If you have 2 apple ids, how do you sign out of one and into the other so you can update the app that was purchased in the other account.  thanks

    If you purchased an app in one account and work mostly in another, how do you switch the purchased app account to update it?
    thanks

    You need to sign out and back in only if you're on your Mac and you want to update the iTunes data.  You'll see a notice saying that there are five (or so) updates but when you go to download them, they're not all present.  So you download them, sign out from one ID and sign back in with the other ID.  Then you can download the remaining ones.
    If you're downloading directly to the iPad, everything is transparent.  It does not matter what ID is configured in Settings.  The iPad automatically chooses the correct ID or IDs when updates are available.

  • How do you store "sent" mail locally and on the server?

    Hello. This is a slightly lengthy...but hopefully someone can help!
    I am using the Mail program in Tiger (Mac OS X 10.4.3) with an IMAP account. I am wondering how you set up the preferences so that the e-mails that you send (outgoing) are stored locally on my computer and also on the server (so that I can .
    So far I have tried checking and unchecking the option to 'store mail on the server' (in the 'Mailbox Behavior' window of the Preference Box). When I uncheck the box, the sent mail is stored ONLY locally on my computer.
    When I check the box so that the mail is stored on the server, I cannot view any copies of the sent mail on my computer, nor can I view the sent mail through my other school account (same account b/c it's IMAP).
    My IMAP account is setup with my school, so I have a folder called 'Sent' that I have programmed so that copies of my sent mail are stored there (viewable locally on any computer that I log-in to). I formerly user Thunderbird (with Mozilla) and it allowed me to save sent mail into that same folder, but I am unable to do so with Mail in the Tiger program.
    I hope this is understandable...anyone able to shed some light on this issue? Thanks!
    PowerBook G4   Mac OS X (10.4.3)  

    Hi tanjo,
    This is a bit of a workaround, but you could set
    mail.app to automatically blind copy to yourself any
    messages you originate (and then use a rule to
    automatically file these messages in a "sent" folder
    of your choice).
    A method to do setup this default bcc is on
    MacOSXhints.com, in this article: Permanently add Reply To headers in
    Mail.app. It references this command line:
    defaults write com.apple.mail
    UserHeaders '{"Bcc" = "[email protected]";
    best of luck,
    ...ben
    PB G4 15 1.67 GHz,
    iBook SE 0.47 GHz   Mac OS X (10.4.3)  
    Hi Ben,
    Thank you very much for the tip. I'm going to give that a try. Happy Holidays!
    --tanjo

  • How to add a New schedule line and update the order quantity?

    Hi all,
       I have to add a new schedule line in VA01/VA02 so that when ther is partial confirmed quantity against a schedule line, we have to create a new schdule line based on the existing so that it will contain confirmed in one and unconfirmed in the other.
    The schedule line will split once the user go to Header data screen in VA01/VA02. So I used USEREXIT_MOVE_FIELD_TO_VBAK  user exits in MV45AFZZ include program.
        I splited the order quantity against the confirmed quantity and added it as new schedule line in the XVBEP internal table and update UPDKZ flags for XVBEP & YVBEP.
      Could anyone tell me is there any other way to do this without updating XVBEP? Because it is affecting some other place because of index table is not updating. How to you think use if update xvbap-etenr_high and update index table IVBEP1 for new line insert into XVBEP instead directly inseritng it into?
    My code as follows:
    xvbep-WMENG = t_temp-WMENG .
    modify xvbep TRANSPORTING WMENG.
    t_temp1- ETENR = '0002'.
    if SY-SUBRC <> 0.
      t_temp1-UPDKZ = UPDKZ_NEW.
      modify xvbep TRANSPORTING WMENG UPDKZ.
    endif.
    With Regards
      Raj

    Have you got thru this one if so please provide me with the solution as i got the same req' ..

  • HT4710 To update this application, sign in to the account you used to purchase it. It was pre-installed, how do I get past this message and update the software?

    To update this application, sign in to the account you used to purchase it. The app was pre-installed, how do I get past this message?

    The the account you used to "purchase" iPhoto is the Apple ID you used to set yoru couputer up with - log into th eApp store using that Apple ID and look under purchases - if you have not accepted the App yet then you will have to accept it first
    LN

  • HT1430 how do you unlock an IPod touch and reset the password

    My daughter has reset her password and now cant remeber it! can anyone tell me in simple terms how to reset please?
    Thanks

    Connect the iOS device to your computer and restore via iTunes. Place the iOS device in Recovery Mode if necessary to allow the restore.
    If recovery mode does not work try DFU mode.
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings
    For how to restore:
    iTunes: Restoring iOS software
    To restore from backup see:
    iOS: How to back up
    If you restore from iCloud backup the apps will be automatically downloaded. If you restore from iTunes backup the apps and music have to be in the iTunes library since synced media like apps and music are not included in the backup of the iOS device that iTunes makes.
    You can redownload iTunes purchases by:
    Downloading past purchases from the App Store, iBookstore, and iTunes Store

  • Just uploaded iso7 , . . .hate it!  Can you change background colours?  How do you add a new item/activity to the schedule? In notes the font has changed, can I change it back and the link colour is now yellow instead of blue, can I change it?  Thanks

    Just uploaded iso7 , . . .hate it!  Can you change background colours?  How do you add a new item/activity to the schedule? In notes the font has changed, can I change it back and the link colour is now yellow instead of blue, can I change it?  Yellow on white is harder to read. Thanks

    Another question. How do you bookmark something.  It was so easy before, why did they change it?  Can I uninstall it?

  • I am considering buying a new MAC laptop to run LOGIC for composition and band live/recording, but which one is best as I do not want to spend too much money? Does it have a line in and how do you monitor sound? Will I need adaptors and a interface?

    Can anybody help?
    I am considering buying a new MAC laptop to run LOGIC for composition and band live/recording, but which one is best as I do not want to spend too much money?
    Does it have a line in and how do you monitor sound?
    Will I need adaptors and an interface?
    Also, I am guessing as Logic only runs on MAC surely then they would not the best spec to recommend to run it?
    I see all the upgrades as additional memory or a faster process?
    Is a retina screen necessary, and why flash based storage against a 1TB hard drive, and a i5 instead of an i7
    The main reason for this purchase is to play live and use backing tracks and record found sounds and make creative songs.
    I hope you can provide some valuable feedback, as I am a longtime MAC user and see upgrades and changes happen regularly but the most important thing is the songs not the equipment.
    I have £500 already and willing to add another 500 to 700 pounds, then software extra.

    Can anybody help?
    I am considering buying a new MAC laptop to run LOGIC for composition and band live/recording, but which one is best as I do not want to spend too much money?
    Does it have a line in and how do you monitor sound?
    Will I need adaptors and an interface?
    Also, I am guessing as Logic only runs on MAC surely then they would not the best spec to recommend to run it?
    I see all the upgrades as additional memory or a faster process?
    Is a retina screen necessary, and why flash based storage against a 1TB hard drive, and a i5 instead of an i7
    The main reason for this purchase is to play live and use backing tracks and record found sounds and make creative songs.
    I hope you can provide some valuable feedback, as I am a longtime MAC user and see upgrades and changes happen regularly but the most important thing is the songs not the equipment.
    I have £500 already and willing to add another 500 to 700 pounds, then software extra.

  • I want to remove the monitor from my 17" Macbook Pro 2008 to use as an external for my Macbook Pro 15" 2012. How can I convert lvds to Thunderbolt and power the monitor?

    I want to remove the monitor from my 17" Macbook Pro 2008 to use as an external for my Macbook Pro 15" 2012. How can I convert lvds to Thunderbolt and power the monitor?

    It's almost impossible.  The new iMacs have a Target Display Mode, but it's built to do that.  Without ripping your screen out, finding an acceptable power supply, frame, and whatever electronics to convert a Thunderbolt signal to the screen, the cost will be much larger than buying a cheaper HiDef monitor that runs with an HDMI to Thunderbolt cable to your MacBook 15.  In fact, you can sell your 17" MBP for a lot of money, unless it's broken or something, buying you a really sweet monitor.
    By the way, I found your answer by searching this forum.  I would suggest using the search function here in the futuere.

  • In Aperture, how do you put a background layer behind text?

    How do you put a background layer behind the text to offset the color of the pic from the text color? Right now, some pics have whites and blacks that drown out the text, making it hard to read...

    I forgot: if you rather want to add a background instead of changing the color of your text:
    To add a background behind a texbox,
    simply edit the layout (Click "Edit Layout", click "+") and add a Photo Box;
    drag the PhotoBox behind your text field.
    click "edit content" and add a picture to the background box.
    You'll need to import a suitable background photo, or crop some suitable background from one of your images.
    Regards
    Léonie

  • In photoshop, how do you make a background a solid color?

    In photoshop, how do you make a background a solid color?

    Select all then edit fill is one way.
    However if you mean the background behind a subject you need to separate the subject from its background the change just the background.  Look for tutorials on replacing background and extracting subjects

  • How do you monitor backup progress

    How can you monitor the progress of a backup? I use timemachine and an external drive  to do my backups on my 09 Macbook pro. I want to be able to see the amount of files transferred and time remaining or any other pertinent info. Not just a spinning wheel.

    I don't know, I use bootable clones myself and it shows me the progress of the backup and updating of files.
    However I can point you to this guy who is the local TM guru
    All about Time Machine
    If you want to learn more about all sorts of backups to diversify your restore options (TM can fail to restore properly), including bootable clones etc. then read my UT here on the subject.
    Most commonly used backup methods explained
    I personally don't use TimeMachine, preferring the more advanced bootable clone options.

Maybe you are looking for

  • How to get File name in Java Callout

    Hi, We are receiving EDI files with random file names through SFTP listening channel. How can we get the file name in the java callout. ~Ismail M

  • Outgoing calls... No go

    This is a bit odd.. I can make outgoing calls, but I cant hear, nor be heard. Incomming is just fine. Music is just fine (speaker and headphones). I can even hear the tones when I dial my voice mail password. I just cant hear anything from the other

  • ITunes keeps going to apps and locks out

    iTunes 10.4 keeps crashing and going to the apps screen even when I  dont want it to go there....then it locks out and becomes unresponsive and I have to force quit the application. How can I get around this??? I am running running it on iMac G5 os 1

  • Using Tabs and Return in TextField

    Hi! I am tying to use a series of TextFields to collect information from the user for a GUI application. Currently, I am adding ActionListeners to the TextFields and when the user enters a value and hits return, then the event is triggered and I am a

  • Macbook pro retina hdmi external comes out with a green tint?

    I have a 2010 old macbook pro and that works fine but the retina comes out with a green tint when pluged in with hdmi.