如何让JButton在同一目录中运行可执行文件?

时间:2014-10-07 01:42:57

标签: java swing jbutton processbuilder

好的,我正在尝试让我的JButton在不同的目录中运行一个可执行文件。它是我编写的以前的控制台应用程序,我希望此按钮运行可执行文件。我是Java编程语言的新手,但这是我的代码。

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。

3 个答案:

答案 0 :(得分:3)

首先看一下ProcessBuilder

Swing是一个单线程框架,因此您不希望在Event Dispatching Thread(调用Process)的当前上下文中启动actionPerformed并且需要执行它在自己的线程上下文中。

这引发了将Process的结果同步回UI的问题,这应该只在EDT的上下文中完成。为此,您应该考虑使用SwingWorker

请查看Concurrency in SwingWorker Threads and SwingWorker了解详情

看看

了解更多示例......

答案 1 :(得分:2)

我所说的是你应该考虑从控制台程序中提取核心逻辑和数据来创建一个或多个模型类,然后在控制台程序或GUI中使用它们。

例如,假设您有一个简单的控制台程序,该程序可以从某人那里获取姓名和出生日期信息:

class SimpleConsole {
   public static void main(String[] args) throws ParseException {
      Scanner scanner = new Scanner(System.in);
      System.out.print("Please enter your name: ");
      String name = scanner.nextLine();

      System.out.print("Please enter your date of birth as mm/dd/yyyy: ");
      String dateString = scanner.nextLine();
      Date dateOfBirth = new SimpleDateFormat("MM/dd/yyyy").parse(dateString);

      Calendar birthday = Calendar.getInstance();
      birthday.setTime(dateOfBirth);
      Calendar today = Calendar.getInstance();
      int age = today.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
      birthday.set(Calendar.YEAR, today.get(Calendar.YEAR));
      if (birthday.compareTo(today) > 0) {
         age--;
      }

      System.out.println("Hello, " + name + ". Your age is: " + age);

   }
}

我要做的第一件事就是从这个程序中提取关键信息和逻辑,并创建一个名为Person的类,它包含名称String,dateOfBirth Date字段和calculateAge()方法:

class Person {
   String name;
   Date dateOfBirth;

   public Person(String name, Date dateOfBirth) {
      this.name = name;
      this.dateOfBirth = dateOfBirth;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public Date getDateOfBirth() {
      return dateOfBirth;
   }

   public void setDateOfBirth(Date dateOfBirth) {
      this.dateOfBirth = dateOfBirth;
   }

   public int getAge() {
      Calendar birthday = Calendar.getInstance();
      birthday.setTime(dateOfBirth);
      Calendar today = Calendar.getInstance();
      int age = today.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
      birthday.set(Calendar.YEAR, today.get(Calendar.YEAR));
      if (birthday.compareTo(today) > 0) {
         age--;
      }
      return age;
   }
}

现在您可以创建一个使用Person的控制台程序:

class BetterConsole {
   public static void main(String[] args) throws ParseException {
      Scanner scanner = new Scanner(System.in);
      System.out.print("Please enter your name: ");
      String name = scanner.nextLine();

      System.out.print("Please enter your date of birth as mm/dd/yyyy: ");
      String dateString = scanner.nextLine();
      Date dateOfBirth = new SimpleDateFormat("MM/dd/yyyy").parse(dateString);

      Person person = new Person(name, dateOfBirth);


      System.out.println("Hello, " + person.getName() + ". Your age is: " + person.getAge());
      scanner.close();
   }
}

但更重要的是,Person类可以很容易地用在你想要的任何类型的GUI程序中。我必须去睡觉所以我现在不能显示GUI,但可能明天。


嗯,这是GUI示例:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;

public class BirthdayGui extends JPanel {
   private static final String PATTERN = "MM/dd/yyyy";
   private JTextField nameField = new JTextField(10);
   private SimpleDateFormat simpleDateFormat = new SimpleDateFormat(PATTERN);
   private JFormattedTextField birthDayField = new JFormattedTextField(simpleDateFormat);
   private PersonTableModel tableModel = new PersonTableModel();
   private JTable table = new JTable(tableModel);

   public BirthdayGui() {
      setLayout(new BorderLayout());;
      add(new JScrollPane(table), BorderLayout.CENTER);
      add(createDataEntryPanel(), BorderLayout.PAGE_END);
   }

   private JPanel createDataEntryPanel() {
      birthDayField.setColumns(nameField.getColumns());
      JPanel dataInPanel = new JPanel();
      dataInPanel.add(new JLabel("Enter Name:"));
      dataInPanel.add(nameField);
      dataInPanel.add(new JLabel("Enter Birthday as " + PATTERN + ":"));
      dataInPanel.add(birthDayField);
      dataInPanel.add(new JButton(new AddPersonAction("Add Person", KeyEvent.VK_A)));
      return dataInPanel;
   }

   private class AddPersonAction extends AbstractAction {
      public AddPersonAction(String name, int mnemonic) {
         super(name);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         String name = nameField.getText();
         Date dateOfBirth = (Date) birthDayField.getValue();
         Person person = new Person(name, dateOfBirth);
         tableModel.addRow(person);
      }
   }

   private class PersonTableModel extends AbstractTableModel {
      public final String[] COL_NAMES = {"Name", "Age"};
      List<Person> personList = new ArrayList<>();

      @Override
      public String getColumnName(int column) {
         return COL_NAMES[column];
      }

      @Override
      public int getColumnCount() {
         return COL_NAMES.length;
      }

      @Override
      public int getRowCount() {
         return personList.size();
      }

      @Override
      public Object getValueAt(int rowIndex, int columnIndex) {
         if (rowIndex < 0 || rowIndex >= getRowCount()) {
            throw new ArrayIndexOutOfBoundsException(rowIndex);
         }
         if (columnIndex < 0 || columnIndex >= getColumnCount()) {
            throw new ArrayIndexOutOfBoundsException(columnIndex);
         }

         Person person = personList.get(rowIndex);
         if (columnIndex == 0) {
            return person.getName();
         } else if (columnIndex == 1) {
            return person.getAge();
         }
         return null;
      }

      @Override
      public java.lang.Class<?> getColumnClass(int column) {
         if (column == 0) {
            return String.class;
         } else if (column == 1) {
            return Integer.class;
         } else {
            return super.getColumnClass(column);
         }
      };

      public void addRow(Person person) {
         personList.add(person);
         int firstRow = personList.size() - 1;
         fireTableRowsInserted(firstRow, firstRow);
      }

   }

   private static void createAndShowGui() {
      BirthdayGui mainPanel = new BirthdayGui();

      JFrame frame = new JFrame("ConsoleGuiEg");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }   
}

答案 2 :(得分:-1)

您必须执行以下操作:

  1. 创建ActionListener并覆盖方法actionPerformed
  2. 在已覆盖的操作执行方法中调用Runtime.getRuntime().exec()
  3. 通过调用ActionListener
  4. button.setActionListener()设置为您的按钮