views:

67

answers:

2

I want to fire a commandline exe with the parameters entered in GUI.

The Process class can be used to fork my required commandline process from the java application. And I used the getInputStream() method of Process object to get the result and got it displayed in the GUI.

private void confirmActionPerformed(java.awt.event.ActionEvent evt) {                                       
        String output;
        try {

           Process p = Runtime.getRuntime().exec("my command line exe with parameters");
            BufferedReader stdInput = new BufferedReader(new
                 InputStreamReader(p.getInputStream()));


            while ((output = stdInput.readLine()) != null) {
                 TextField.setText(TextField.getText()+output+"\n");
             }

        }
        catch (IOException e) {
            System.out.println("Exception in Process");
            e.printStackTrace();
        }

    }

This is my code which is an event listener of a button pressed event and I attempted to display the result of the process in the text field (java swing component).

This process actually runs for quite a long time and shows some statistics as and when it runs when run in command line. But when i attempt it in GUI with the above code Im getting the entire consolidated result only after the process finish running. Im not getting the TextField updated as and when it is executing.

Plz help me. Im not getting where it goes wrong..

+1  A: 

This is because the whole thing is done by the Swing event-handling thread.

Perhaps should you consider creating a separate thread and update the TextField with a SwingUtilities.invokeLater().

Maurice Perry
A: 

As Maurice already pointed out, you shouldn't be doing intensive processing on the UI thread. The SwingWorker class helps with that. It's part of the standard API since 1.6. There is also a backport to 1.5 if you can't use 1.6.

This class makes it easier to put some processing task on another thread and display the result later so that your GUI doesn't block in the meantime. You can also use SwingUtilities.invokeLater() directly, of course, as suggested by Maurice, but for me SwingWorker is the way to go as it is quite easy and apparently the new standard way of doing this kind of thing.

Robert Petermeier