我正在开发一个 Java 程序,我想在用户单击按钮时执行一些命令行代码。我必须编写代码来执行我的命令行代码和按钮代码,但我现在不知道如何将两者结合起来:我的按钮代码如下所示:
private JButton setup;
public ProgramGUI(){
UsedHandler handler = new UsedHandler();
setup.addActionListener(handler);
}
private class UsedHandler implements ActionListener{
@Override
public void actionPerformed(ActionEvent event) {
if(event.getSource()==setup)
JOptionPane.showMessageDialog(null, "Everything fine!");
}
}
这就是我的命令行代码:
try {
Runtime rt = Runtime.getRuntime();
//Process pr = rt.exec("cmd /c dir");
Process pr = rt.exec("c:\\helloworld.exe");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
谢谢!