0

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

运行批处理文件代码:

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

1 回答 1

2

您正在阻止事件调度线程,这会阻止它处理任何重绘请求。

您应该将“批处理”代码移动到后台线程,类似 a 的东西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();
于 2013-02-28T06:47:45.067 回答