从jTextArea上的shell命令获取结果

时间:2016-06-16 10:33:51

标签: java swing shell cmd jtextarea

我必须从java swing app执行shell命令窗口并获得实时结果:

String cmd = jTextField1.getText();

StringBuffer output = new StringBuffer();

Process p;
try {
    p = Runtime.getRuntime().exec(cmd);

    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

    String line = "";
    while ((line = reader.readLine()) != null) {
        System.out.println("" + line);
        jTextArea1.append(line + "\n");
    }

} catch (Exception e) {
    e.printStackTrace();
}

问题是在jTextArea中写入是在执行完成之后不是像System.out.println(..)那样的实时。

2 个答案:

答案 0 :(得分:4)

当您从事件调度线程(EDT)外部更新swing组件时,您应该使用SwingWorker或调用SwingUtilities.invokeLater(),如下所示:

while ((line = reader.readLine()) != null) {
    final String appendLine = line + "\n";
    System.out.println("" + line);
    SwingUtilities.invokeLater(new Runnable(){ 
        public void run(){    
            jTextArea1.append(appendLine);
        }
    });
} 

答案 1 :(得分:0)

尝试创建一个Thread并使用Thread.sleep()来实时更新JTextArea。

创建如下的子类

class Work implements Runnable {

        String cmd;

        Work(String c) {
            this.cmd = c;
        }

        @Override
        public void run() {
            Process p;
            try {
                p = Runtime.getRuntime().exec(cmd);

                BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

                String line = "";
                while ((line = reader.readLine()) != null) {
                    System.out.println("" + line);
                    Thread.sleep(500);
                    jTextArea1.append(line + "\n");
                }

            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

按以下方式更改代码

String cmd = jTextField1.getText();
StringBuffer output = new StringBuffer();
new Thread(new Work(cmd)).start()