gpt4 book ai didi

java - 执行 .bat 文件时启用按钮

转载 作者:行者123 更新时间:2023-12-02 07:14:18 24 4
gpt4 key购买 nike

我有一个带有打开按钮和后退按钮的表单。我通过打开按钮打开批处理文件,在执行批处理文件时,其他按钮被禁用。我想启用这些按钮。请帮助我。

运行批处理文件代码:

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);
}

最佳答案

您正在阻塞事件分派(dispatch)线程,这会阻止它处理任何重绘请求。

您应该将“批处理”代码移动到后台线程,例如 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();

关于java - 执行 .bat 文件时启用按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15129107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com