2014-10-07 67 views
0

好吧,我试图让我的JButton在一个不同的目录下运行一个可执行文件。这是我写的前一个控制台应用程序,我希望使用此按钮来运行可执行文件。我对Java编程语言相当陌生,但这里是我的代码。如何让JButton在同一目录下运行可执行文件?

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。

+0

可能重复[Java运行的一个bash shell脚本](http://stackoverflow.com/questions/13707519/running-a- bash-shell-script-in-java) – StackFlowed 2014-10-07 01:48:20

+1

对不起,但你的代码没有意义,看起来像一个编程“想法的飞行” - 随机编程思想挤在一起。至于你的问题,你说的“运行一个控制台程序”究竟意味着什么?这是一个Java控制台程序吗?它是一种用户通过控制台与程序交互的程序类型吗?如果是这样,从GUI运行它的目的是什么?这些细节将有助于他人更好地理解您的问题。 – 2014-10-07 01:48:33

+0

请编辑您的代码。看起来你粘贴了一个块两次。 – 2014-10-07 01:49:47

回答

3

首先看看ProcessBuilder

Swing是一个单线程的框架,所以你不会希望将事件调度线程(其中actionPerformed的叫法),将需要它自己的线程上下文中执行它的当前环境中启动Process

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

看看Concurrency in SwingWorker Threads and SwingWorker更多细节

看一看

更多的例子...

+1

谢谢我一定会考虑这一点,我将不得不学习ProcessBuilder,但我相信这不是世界上最糟糕的事情,也不是最难学的东西。再次感谢你的回答 – Groax 2014-10-07 02:10:26

-1

你必须做到以下几点:

  1. 创建ActionListener和覆盖的方法actionPerformed
  2. 调用Runtime.getRuntime().exec()在你重写的行动所进行的方法。
  3. 通过调用button.setActionListener()
+3

如果你不小心,注意你的用户界面来到尖锐的holt ... – MadProgrammer 2014-10-07 02:14:11

+0

*“调用'Runtime.getRuntime().exec()'..”*你在编码什么, Java 1.4?!?对于Java 1.5以上的版本,使用'ProcessBuilder',因为它使得代码变得更加容易(与此建议相反,这种建议比失败更为常见,甚至在工作时也会阻止EDT)。 -1 – 2014-10-07 05:20:44

2

我想说的是,你应该考虑提取您的控制台程序的核心逻辑和数据来创建一个模型类或类,然后使用这些设置ActionListener你的按钮在您的控制台程序或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); 

    } 
} 

我做的是首先要提取此程序中的关键信息和逻辑,使一类,说叫人持有一个名称的字符串,一出生日期日期字段和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; 
    } 
} 

,现在你可以创建一个使用人一个控制台程序:

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(); 
     } 
     }); 
    } 
} 
相关问题