【问题标题】:Sending a command line command from JButton? [duplicate]从 JButton 发送命令行命令? [复制]
【发布时间】:2016-05-19 08:35:47
【问题描述】:

我想构建类似 apache xampp 控制面板的东西。我想创建自己的控制面板来启动/停止我的服务器。

我正在使用 Eclipse GUI Builder,我尝试在线搜索有关此问题的帮助,但找不到任何东西。谁能帮帮我?

例如,通常当我启动服务器时,我会转到命令提示符,转到目录并键入 run.bat。停止服务器时,我必须执行 ctrl + c。

如何通过单击一个 JButton(启动服务器)和另一个 JButton(停止服务器)来实现此目的?

我的编码没有太多内容,因为它是默认的 Eclipse Swing GUI 生成的代码。

【问题讨论】:

  • 可能的解决方案:stackoverflow.com/questions/8496494/…
  • ProcessBulder 将是首选解决方案,任何其他解决方案都需要大量煮沸电镀和潜在问题
  • 那么如果我有一个run.bat的动态目录,我可以为用户创建一个jtextfield,让用户进入run.bat所在的目录,然后监听textfield吗?单击按钮后从该文本字段目录运行 run.bat 之后?

标签: java eclipse swing user-interface


【解决方案1】:

runtime.exec 方法中的命令取决于您的操作系统,但在正常情况下,您可以尝试以下操作:

    JButton startServer = new JButton();
    startServer.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Runtime runtime = Runtime.getRuntime();
            try {
                // Here exec your bat file
                runtime.exec("Path_To_Your_Bat_File");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    });

    JButton stopServer = new JButton();
    stopServer.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Runtime runtime = Runtime.getRuntime();
            try {
                //Here get your process id and kill it
                runtime.exec("Get_Process & Kill");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    });

【讨论】:

  • 谢谢!我是否能够收听文本字段以便路径可以是动态的?
【解决方案2】:
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("COMMAND_HERE");

http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 2014-04-02
    • 2010-11-14
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    相关资源
    最近更新 更多