闲云无衣
无衣的笔记

原文出处:http://blog.csdn.net/muiltmeta/archive/2002/05/08/16660.aspx

前一段时间看了《程序员》第 3 Java 专家门诊中怎样调用其它的程序,我把其解答代码放到一个程序中,如下示:

import java.lang.*;

 

public class runProg{

public static void main(String[] args){

       try{

         Runtime rt=Runtime.getRuntime();

         rt.exec("NotePad");

       }catch(Exception e){}

}

}

 

 

 

 

 

 

 

 

 

 

 

 


在命令符下编译运行,直接调用了记事本应用程序,没有任何问题。

但在图形用户的应用程序中,就不能编译,代码示例如下:

  void jButton1_actionPerformed(ActionEvent e) {

    // 下是解答代码

try{

       Runtime rt=Runtime.getRuntime();

       rt.exec("NotePad");

    }catch(Exception e){

}

// 上是解答代码

  }

 

 

 

 

 

 

 

 

 

 

 


就上面的代码而言,只是说明了调用其它程序的基本方法,但是这段代码根本不能被编译过去,在 Jbuilder 中的编译错误如下:

"Frame2.java": Error #: 469 : variable e is already defined in method jButton1_actionPerformed(java.awt.event.ActionEvent) at line 50, column 18

 

 

 

 


看到这个编译错误也许认为是按钮的事件定义错误,实际上是 AWT Component 的事件是线程安全级的,不允许直接使用另外进程或线程,因 Swing 中的组件是从 AWT 中继承来的,所以也不允许直接使用。解决办法只有使用一个新线程。代码如下示:

  void jButton1_actionPerformed(ActionEvent e) {

    //must be use a new thread.

    Thread t = new Thread(new Runnable(){

    public void run(){

       try {

        Runtime rt = Runtime().getRuntime();

        rt.exec(“notepad”);

        } catch (IOException e) {

        System.err.println("IO error: " + e);

      }

    }

    });

    t.start();

 

  }

但是这段代码还是不能被编译,错误提示如下:

"Frame1.java": Error #: 300 : method Runtime() not found in anonymous class of method jButton1_actionPerformed(java.awt.event.ActionEvent) at line 74, column 22

 

 

 

 


看到这段代码,认为没有发现 Runtime() ,或者没有包含 Runtime 所在的包。但实际上是 java 每个 Application 都有一个自己的 Runtime ,所以不允许显式声明和使用另外一个。其实,许多文章也都是这么介绍的。在这里必须使用 Process 来启用另外一个进程使用 Runtime 。代码示例如下:

  void jButton1_actionPerformed(ActionEvent e) {

    //must be use a new thread.

    Thread t = new Thread(new Runnable(){

    public void run(){

      try {

        //String[] arrCommand = {"javaw", "-jar", "d:/Unicom/Salary/Salary.jar"};

              // Process p = Runtime.getRuntime().exec(arrCommand);

        Process p = Runtime.getRuntime().exec("notepad");

        p.waitFor();

        System.out.println("return code: " + p.exitValue());

      } catch (IOException e) {

        System.err.println("IO error: " + e);

      } catch (InterruptedException e1) {

        System.err.println("Exception: " + e1.getMessage());

      }

    }

    });

    t.start();

 

  }

运行后,点击 jButton1 调用了 Windows 中的记事本应用程序。这里,新线程使用了 Runnable 接口,这是一种常用的技巧。另外,还必须要捕获 IOException InterruptedException 两个异常。对于调用带有参数的复杂程序,要使用字符串数组代替简单的字符串,我在上面的代码注释了。

posted on 2007-03-14 15:24 无衣 阅读(711) 评论(1)  编辑  收藏 所属分类: Java