JButton在目录中执行exe文件

时间:2013-12-12 20:06:26

标签: java swing process jbutton

假设我有一个名为“Play”的JButton,当我点击它时,它应该启动C:/play.exe。我该如何设法做到这一点?我很想看到一个例子。

2 个答案:

答案 0 :(得分:0)

查看ProcessBuilder的javadoc,其中包含如何在底层系统上创建进程的示例。

从那里可以轻松地将其连接到按钮的ActionEvent

答案 1 :(得分:0)

查看Runtime.getRuntime()。exec()方法。见这个例子:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

public class Main extends JFrame {
   public Main() throws HeadlessException {
     setSize(200, 200);
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     setLayout(new FlowLayout(FlowLayout.LEFT));

     JLabel label = new JLabel("Click here: ");
     JButton button = new JButton();

     button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent actionEvent) {
           Process process = null;
           System.exit(0);
           try {
               process = Runtime.getRuntime().exec("C:/play.exe");
           } catch (IOException e) {
               e.printStackTrace();
           }

        }
     });
  }

  public static void main(String[] args) {
      new Main().setVisible(true);
  }
}
相关问题