如何使JButton在同一目录中运行可执行文件? [英] How do I make a JButton run an executable in the same directory?

查看:81
本文介绍了如何使JButton在同一目录中运行可执行文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我正在尝试让我的JButton在其他目录中运行可执行文件.这是我编写的先前的控制台应用程序,我希望该按钮运行可执行文件.我是Java编程语言的新手,但这是我的代码.

Okay, I'm trying to make my JButton run an executable in a different directory. It is a previous console application I wrote and I want this button to run the executable. I'm fairly new to the Java programming language but here is my code.

import java.util.*;

import javax.swing.*;

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



public class main
{
    public static void main(final String[] args) throws IOException {
        JFrame f = new JFrame("Test");
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(500, 500);
        JPanel p = new JPanel();
        JButton b1 = new JButton("Calculate");
        f.add(p);
        p.add(b1);
        Process proce = Runtime.getRuntime().exec("C:/Ctest.exe");
    }
    private static void test1() {
        // TODO Auto-generated method stub

    }
    {
        JFrame f = new JFrame("Test");
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(500, 500);
        JPanel p = new JPanel();
        JButton b1 = new JButton("Calculate");
        f.add(p);
        p.add(b1);
        b1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {

            }
        });
     }
}

如果您对我有任何提示,请随时告诉我.我使用的是Eclipse IDE.

Also if you have any tips for me please feel free to tell them to me. I use the eclipse IDE.

推荐答案

首先查看 Swing是一个单线程框架,因此您不想在事件调度线程(在其中调用actionPerformed)的当前上下文中启动Process,而需要在其自身中执行它线程上下文.

Swing is a single threaded framework, so you won't want to start the Process within the current context of the Event Dispatching Thread (in which the actionPerformed is called) and will need to execute it within it's own thread context.

这引起了将结果从Process返回到UI的同步问题,这仅应在EDT的上下文中完成.为此,您应该考虑使用SwingWorker

This raises the issue of synchronising results from the Process back to the UI, which should only ever be done within the context of the EDT. To this end, you should consider using a SwingWorker

看看 Swing中的并发工作线程和SwingWorker 了解更多详情

看看

  • Printing a Java InputStream from a Process
  • Swing message doesn't get displayed until after Runtime.getRuntime().exec() finishes execution
  • Enabling buttons while executing .bat file

更多示例...

这篇关于如何使JButton在同一目录中运行可执行文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆