我目前正在尝试将进度条插入到我的java gui中。但是,当我单击“开始”按钮时,进度条不会运行。在cmd中运行的所有不同批处理文件都必须完成,然后运行进度条。但重点是什么?我希望它在按下“START”按钮时运行,当cmd中运行的所有不同批处理文件结束时,进度条也会停止。
这是我的代码:
JLabel ProgressBar = new JLabel("Progress Bar: ");
ProgressBar.setFont(new Font("Arial", Font.BOLD, 12));
ProgressBar.setBounds(100, 285, 180, 53);
contentPane.add(ProgressBar);
final JProgressBar aJProgressBar = new JProgressBar(JProgressBar.HORIZONTAL);
aJProgressBar.setBounds(185,305,184,15);
contentPane.add(aJProgressBar);
//when start button is selected
btnStart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent args)
{
//the process starts
JStartTimeTextField.setText(dateFormat.format(date));
//the progress bar should show it running (by right)
aJProgressBar.setIndeterminate(true);
try
{
//create new process
String command = "cmd /c start /wait" +DetectDrive+"\\starting.bat";
//run process
Process p = Runtime.getRuntime().exec(command);
//cause this process to stop until process p is terminated
p.waitFor();
}
catch (IOException | InterruptedException e1)
{
e1.printStackTrace();
}
......
Date newDate = new Date();
JStartTimeTextField.setText(dateFormat.format(newDate));
//the progress bar should stop running (by right)
//aJProgressBar.setIndeterminate(false);
}
});
因此,右键...单击“开始”按钮时,应显示startTime并运行进度条。但是,只有当cmd中的所有批处理文件都完成运行时,才会显示startTime。
但就目前而言,进度条是我的首要任务。如何点击“开始”按钮,进度条运行,完成后,进度条会停止?
非常感谢任何帮助!
答案 0 :(得分:0)
您正在使用相同的线程来更新JProgressBar
并运行脚本。问题是你等待Process
终止(p.waitFor()
),因此,线程将等待而不是更新JProgressBar
。正确的解决方案是使用SwingWorker 。但我认为你可以通过启动一个新的Thread
来运行你的srcipt来运行。
类似的东西:
public void actionPerformed(ActionEvent args)
{
//the process starts
JStartTimeTextField.setText(dateFormat.format(date));
//the progress bar should show it running (by right)
aJProgressBar.setIndeterminate(true);
new Thread()
{
public void run()
{
try
{
//create new process
String command = "cmd /c start /wait" +DetectDrive+"\\starting.bat";
//run process
Process p = Runtime.getRuntime().exec(command);
//cause this process to stop until process p is terminated
p.waitFor();
}
catch (IOException | InterruptedException e1)
{
e1.printStackTrace();
}
}
}.start();
......
Date newDate = new Date();
JStartTimeTextField.setText(dateFormat.format(newDate));
//the progress bar should stop running (by right)
//aJProgressBar.setIndeterminate(false);
}