如何从gui启动控制台程序?

时间:2012-04-17 20:58:14

标签: java user-interface console

这是在BlueJ中创建的作业,并作为包含BlueJ包的zip文件提交。

在包中有几个独立的控制台程序。我正在尝试创建另一个“控制面板”程序 - 一个带有单选按钮的gui来启动每个程序。

以下是我尝试过的两个监听器类:

private class RadioButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource() == arraySearchButton)
        {
            new ArraySearch();
        }//end if
            else if(e.getSource() == workerDemoButton)
            {
                new WorkerDemo();
            }//end else if
    }//end actionPerformed
}//end class RadioButtonListener

private class RunButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        if(arraySearchButton.isSelected())
        {
            new ArraySearch();
        }//end if
            else if(workerDemoButton.isSelected())
            {
                new WorkerDemo();
            }//end else if
    }//end actionPerformed
}//end class RunButtonListener

提前致谢!

1 个答案:

答案 0 :(得分:1)

假设您正在尝试启动.EXE控制台应用程序,这里有一些可以帮助您的代码。请参阅下面的说明。

import java.io.*;


public class Main {

       public static void main(String args[]) {

            try {
                Runtime rt = Runtime.getRuntime();
                //Process pr = rt.exec("cmd /c dir");
                Process pr = rt.exec("c:\\helloworld.exe");

                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();
            }
        }
}

首先,您需要处理当前运行的java应用程序,并为此创建一个运行时对象并使用Runtime.getRuntime()。然后,您可以声明一个新进程并使用exec调用来执行正确的应用程序。

bufferReader将帮助打印生成的进程的输出并将其打印在java控制台中。

最后,pr.waitFor()将强制当前线程等待进程pr终止,然后再继续。 exitVal包含错误代码(如果有的话)(0表示没有错误)。

希望这有帮助。