Enabling buttons while executing .bat file

前端 未结 1 714
忘掉有多难
忘掉有多难 2021-01-27 05:10

I have a form with an open and a back button. I open my batch file through the open button, while the batch file is executing, the other buttons are disabled. I want to enable t

相关标签:
1条回答
  • 2021-01-27 05:58

    You're blocking the event dispatching thread, which is preventing it from processing any repaint requests.

    You should move you "batch" code to a background thread, something like a SwingWorker would be excellent for this problem.

    Added example

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

    When you're ready to execute your batch program, simply do something like...

    back.setEnabled(false);
    new BatchRunner().execute();
    
    0 讨论(0)
提交回复
热议问题