我有一个带有开启和后退按钮的表单。我通过打开按钮打开我的批处理文件,当批处理文件正在执行时,其他按钮被禁用。我想启用这些按钮。请帮帮我。
运行批处理文件代码:
private void openActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// back.setEnabled(true);
String filename = "C:\\JMeter Project\\jakarta-jmeter-2.5.1\\bin\\jmeter.bat";
String command = filename;
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
System.out.println(line);
}
back.setEnabled(true);
JOptionPane.showMessageDialog(null, "Batch file executed successfully.....!!!!");
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Batch file execution failed.");
}
// Form f=new Form();
// back.action(f.setVisible(true),null);
}
后退按钮代码:
private void backActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
close();
sms_sound s = new sms_sound();
//s.setVisible(true);
Form f = new Form();
f.setVisible(true);
// back.setEnabled(true);
}
答案 0 :(得分:2)
您正在阻止事件调度线程,这阻止它处理任何重绘请求。
您应该将“批处理”代码移到后台线程,像SwingWorker
这样的问题对于这个问题非常有用。
添加了示例
public class BatchRunner extends SwingWorker<Integer, String> {
@Override
protected Integer doInBackground() throws Exception {
String filename = "C:\\JMeter Project\\jakarta-jmeter-2.5.1\\bin\\jmeter.bat";
String command = filename;
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
publish(line);
}
return process.exitValue();
}
@Override
protected void process(List<String> chunks) {
// You can process the output produced
// the doBackgroundMethod here within the context of the EDT
}
@Override
protected void done() {
try {
Integer result = get();
if (result == 0) {
JOptionPane.showMessageDialog(null, "Batch file executed successfully.....!!!!");
} else {
JOptionPane.showMessageDialog(null, "Batch file returned an exit value of " + result);
}
} catch (InterruptedException | ExecutionException | HeadlessException interruptedException) {
JOptionPane.showMessageDialog(null, "Batch file execution failed.");
}
back.setEnabled(true);
}
}
当您准备执行批处理程序时,只需执行类似......
的操作back.setEnabled(false);
new BatchRunner().execute();