Linux 终端输出到 JTextpane

Linux terminal Output to JTextpane

我目前正在寻找在我 运行 以下代码时可以实际将信息打印到 jTextpane 的方法。当我按下 运行 按钮时,程序实际上挂起并且没有显示输出。有没有办法绕过它或修复它?

 private void ScannetworkActionPerformed(java.awt.event.ActionEvent evt) {  
 Process p = null;
        try {
            p = Runtime.getRuntime().exec("ipconfig /all");
    } catch (IOException ex) {
        Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        p.waitFor();
    } catch (InterruptedException ex) {
        Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
    }
    BufferedReader buf = new BufferedReader(new InputStreamReader(
        p.getInputStream()));
String line = "";
String output = "";

try {
    while ((line = buf.readLine()) != null) {
        output += line + "\n";
    }     } catch (IOException ex) {
        Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
        }
    nninfo.setText(output);        

截图:

您需要在单独的线程中执行该进程,否则它将在 UI-Thread 中执行,并且只要进程是 运行 就会阻止任何刷新事件。在 swing 中,这通常是通过使用 SwingWorker 来完成的(只需 google,您可能会找到一些不错的教程)。

此外 Process.waitFor() 将等待进程完成,之后 您将阅读进程输出的内容。也就是说,只要进程是 运行,您就不会获得任何更新。要使用来自 运行 进程的信息更新您的 UI,您必须在等待进程完成之前从进程的输入流中读取数据。也许 this question and the accepted answer 会帮助您了解如何执行此操作。

这就是您的 SwingWorker 的样子。我还没有测试过,但它应该会给你一些想法:

public class ScannetworkWorker
    extends SwingWorker<String, String>
{

  private final JTextPane mOutputPane;

  public ScannetworkWorker(JTextPane aOutputPane)
  {
    super();
    mOutputPane = aOutputPane;
  }

  @Override
  protected String doInBackground() throws Exception
  {
    Process p = null;
    try
    {
      p = Runtime.getRuntime().exec("ipconfig /all");
    }
    catch (IOException ex)
    {
      Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
    }

    BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = "";
    String output = "";

    try
    {
      while ((line = buf.readLine()) != null)
      {
        publish(line);
        output += line + "\n";
      }
    }
    catch (IOException ex)
    {
      Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
    }

    try
    {
      p.waitFor();
    }
    catch (InterruptedException ex)
    {
      Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
    }

    return output;
  }

  @Override
  protected void process(List<String> aChunks)
  {
    final String intermediateOutput = aChunks.stream().collect(Collectors.joining("\n"));
    final String existingText = mOutputPane.getText();

    final String newText = existingText + "\n" + intermediateOutput;

    mOutputPane.setText(newText);
  }

}