How can I make this method update the GUI within my loop?

前端 未结 2 1528
不知归路
不知归路 2020-12-22 10:12

I\'m making a program that runs a few cmd commands (USMT and file transfer)

It\'s working fine, but I only get the last line from the cmd in my text box and only af

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-22 10:15

    At the moment, you are reading the command output using readLine(), and then you are directly putting it into setText().

    Update in realtime

    To make the code update it in real time, we are defining a new Thread and use that thread to read over the OutputStream over the socket:

    public void load() throws IOException {
    
     Thread t = new Thread(() -> {
      try {
       ProcessBuilder builder = new ProcessBuilder(
        "cmd.exe", "/c", "cd \"C:\\usmt\" && loadstate.bat");
       builder.redirectErrorStream(true);
       Process p = builder.start();
       BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
       String line;
       while (true) {
        line = r.readLine();
        if (line == null) {
         break;
        }
        String l = line;
        SwingUtilities.invokeLater(new Runnable() {
         public void run() {
          cOut.setText(l);
         }
        });
        System.out.println(line);
       }
      } catch (IOException ex) {
       ex.printStackTrace(); //Add a better error handling in your app
      }
     });
     t.start();
    }
    

    Above, we define a new thread that is used to read the lines.

    Outputting all the lines

    Sometimes, you need to put all the lines the command is printing on screen, this is easy to do using a StringBuilder:

    String line;
    StringBuilder total = new StringBuilder();
    while (true) {
     line = r.readLine();
     if (line == null) {
      break;
     }
     total.append(line).append('\n');
     cOut.setText(total.toString());
     System.out.println(line);
    }
    

    The above uses a StringBuilder to temporary store the finished result, before writing it to the screen.

提交回复
热议问题