问题
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) {
}
});
}
}
Also if you have any tips for me please feel free to tell them to me. I use the eclipse IDE.
回答1:
Start by taking a look at ProcessBuilder.
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.
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
Take a look at Concurrency in Swing and Worker Threads and SwingWorker for more details
Have a look at
- 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
for more examples...
回答2:
What I'm saying is that you should consider extracting the core logic and data from your console program to create a model class or classes, and then use them in your console program or in a GUI.
For instance say you had a simple console program that got name and birth date information from someone:
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);
}
}
First thing I'd do would be to extract the key information and logic from this program and make a class, say called Person, that holds a name String, a dateOfBirth Date field, and a calculateAge() method:
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;
}
}
and now you can create a console program that uses 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();
}
}
But more importantly, the Person class can be easily used in any type of GUI program that you desire. I must go to sleep so I can't show a GUI now, but may tomorrow.
Ah heck, here's the GUI example:
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();
}
});
}
}
回答3:
You have to do the following:
- Create an
ActionListener
and override the methodactionPerformed
- Call the
Runtime.getRuntime().exec()
in your overridden action performed method. - Set the
ActionListener
to your button by callingbutton.setActionListener()
来源:https://stackoverflow.com/questions/26227393/how-do-i-make-a-jbutton-run-an-executable-in-the-same-directory