打开GUI

时间:2015-07-07 14:00:46

标签: java macos user-interface netbeans terminal

我正在尝试在netbeans中编写一个用于在命令行上执行程序的java GUI,并且当前将这段代码分配给一个按钮

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try
        {
        Runtime rt = Runtime.getRuntime();
            Process pr = rt.exec("open -a /Applications/Utilities/Terminal.app");


            BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

            String line=null;

            while((line=input.readLine()) != null)
            {
            System.out.println(line);
            }

            int exitVal = pr.waitFor();
            System.out.println("Exited with error code "+exitVal);
            } 
     catch(Exception e)
            {
            System.out.println(e.toString());
            e.printStackTrace();
            }
}

这会打开终端,但是我想知道如何在按下按钮的同时将命令输入终端(例如:" ls"," cd" ," javac"等)谢谢!

更新: @Codebender我的代码现在看起来像这样。

Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("open -a /Applications/Utilities/Terminal.app");
            new PrintStream(pr.getOutputStream).println("ls");

我收到错误"找不到符号,符号:变量getOutputStream,location:变量pr类型进程"和getOutputStream下的红线。有什么想法吗?

@Codebender那应该是这样吗?

new PrintStream(pr.getOutputStream{println("ls")});

1 个答案:

答案 0 :(得分:0)

使用可以使用outputStream写入终端。用打印流包装它以使事情变得更容易。

Process pr = rt.exec("open -a /Applications/Utilities/Terminal.app");
PrintStream ps = new PrintStream(pr.getOutputStream());
ps.println("ls" + System.lineSeparator());
// Follow with the reading of output from terminal.

如果你的Terminal.app是默认的linux终端,而不是打开一个新终端,你可以尝试,

Process pr = rt.exec("ls");
// Follow with the reading of output.