Java 在等待另一个进程结束时显示JFrame
在我的应用程序中,当按下备份按钮时,创建数据库备份需要一些时间,因此我需要显示一个包含“请稍候…”消息的jframe,并希望在备份过程完成后将其释放。下面是我的代码,但它从未显示jframe,但应用程序在进程结束之前一直处于停滞状态Java 在等待另一个进程结束时显示JFrame,java,multithreading,Java,Multithreading,在我的应用程序中,当按下备份按钮时,创建数据库备份需要一些时间,因此我需要显示一个包含“请稍候…”消息的jframe,并希望在备份过程完成后将其释放。下面是我的代码,但它从未显示jframe,但应用程序在进程结束之前一直处于停滞状态 try { WaitView wait = new WaitView(); wait.setLocationRelativeTo(null); wait.setVisible(true);
try {
WaitView wait = new WaitView();
wait.setLocationRelativeTo(null);
wait.setVisible(true);
Process p = Runtime.getRuntime().exec("cmd /c mysqlbackup.bat", null, new File("C:\\MySQLBackups"));
p.waitFor();
wait.dispose();
MessageService.showMessageDialog(MessageService.BACKUP_SUCCESSFUL, "Successful", "info");
} catch (Exception ex) {
ex.printStackTrace();
}
将代码包装在SwingUtilities.invokeLater()中
但实际上,最好在单独的线程中运行辅助任务。查看SwingWorker示例。按照StanislavL上面的指示,我已按如下方式修改了代码,并且成功了
final WaitView wait = new WaitView();
wait.setLocationRelativeTo(null);
wait.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Process p = Runtime.getRuntime().exec("cmd /c mysqlbackup.bat", null, new File("C:\\MySQLBackups"));
p.waitFor();
wait.dispose();
MessageService.showMessageDialog(MessageService.BACKUP_SUCCESSFUL, "Successful", "info");
} catch (InterruptedException ex) {
Logger.getLogger(HomeView.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(HomeView.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
final WaitView wait = new WaitView();
wait.setLocationRelativeTo(null);
wait.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Process p = Runtime.getRuntime().exec("cmd /c mysqlbackup.bat", null, new File("C:\\MySQLBackups"));
p.waitFor();
wait.dispose();
MessageService.showMessageDialog(MessageService.BACKUP_SUCCESSFUL, "Successful", "info");
} catch (InterruptedException ex) {
Logger.getLogger(HomeView.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(HomeView.class.getName()).log(Level.SEVERE, null, ex);
}
}
});