有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在等待另一个进程结束时显示JFrame

在我的应用程序中,当按下备份按钮时,创建数据库备份需要一些时间,因此我需要显示一个包含“请稍候…”的jframe消息,并希望在备份过程完成后对其进行处理。下面是我的代码,但它从未显示jframe,但应用程序在进程结束之前一直处于停滞状态

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

共 (2) 个答案

  1. # 1 楼答案

    好的,按照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);
                    }
                }
            });
    
  2. # 2 楼答案

    用SwingUtilities包装代码。调用器()

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

    但实际上,最好在单独的线程中运行成功任务。查看SwingWorker示例