2013-04-23 103 views
0

我正在研究一个Java程序,并且我想在用户单击按钮时执行一些命令行代码。我必须代码来执行我的命令行代码和按钮的代码,但我不知道现在怎么都结合: 我的按钮的代码如下所示:在按钮上点击运行命令行代码

private JButton setup; 
public ProgramGUI(){ 
    UsedHandler handler = new UsedHandler(); 
    setup.addActionListener(handler); 

} 
private class UsedHandler implements ActionListener{ 

    @Override 
    public void actionPerformed(ActionEvent event) { 
     if(event.getSource()==setup) 
      JOptionPane.showMessageDialog(null, "Everything fine!"); 
    } 
} 

这就是我的命令行代码:

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

谢谢!

回答

0

把你EXEC代码的方法和从你的按钮

public void yourProcess() { 
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(); 
    } 
} 

执行的动作里调用它,然后使用方法

@Override 
public void actionPerformed(ActionEvent event) { 
    if(event.getSource()==setup){ 
     yourProcess(); 
     JOptionPane.showMessageDialog(null, "Everything fine!"); 
    } 
} 
2

为了防止命令行代码需要很多时间和阻止AWT,你需要多线程。

private class UsedHandler implements ActionListener, Runnable { 
    private JButton setup; 
    private Executor executor = Executors.newSingleThreadExecutor(); 

    @Override 
    public void actionPerformed(ActionEvent event) { 
     if (event.getSource() == setup) { 
      executor.execute(this); 
     } 
    } 

    @Override 
    public void run() { 
     try { 
      Runtime rt = Runtime.getRuntime(); 
      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(); 
     } 
    } 
}