Search code examples
javaswingfocusprogressmonitor

How to use ProgressMonitor window without losing focus on the main JFrame?


I don't know how to do that, because ProgressMonitor window is self-invoked (after 2 seconds, if necessary) and I don't have any control when and if it will open. Therefore I don't have a clue how to make it open in background, so the focus stays on the main JFrame.

MyFile file = panel.getFilesystem().getFile(panel.getDirectory()+fileName);
if(file.isDirectory()){
    final ProgressMonitor monitor = new ProgressMonitor((Component)event.getSource(), 
            "Determining the size of "+file.getName(), "Initializing...", 0, 100);
    monitor.setMillisToPopup(500);
    monitor.setMillisToDecideToPopup(200);
    final DirectorySizeWorker worker = new DirectorySizeWorker(file, table, monitor, table.getSelectedRow(), 2);
    worker.execute();
    worker.addPropertyChangeListener(
             new PropertyChangeListener() {
                 public  void propertyChange(PropertyChangeEvent event) {
                     if ("progress".equals(event.getPropertyName())) {
                         monitor.setProgress((Integer)event.getNewValue());
                         monitor.setNote((Integer)event.getNewValue() + "% completed");
                     }
                     if("state".equals(event.getPropertyName())){
                         monitor.close();
                     }
                 }
             });
}

monitor is monitoring behaviour of worker. worker is a SwingWorker implementation trying to deremine the file size (in this particular case file is a directory, that's why I assume it may take a long time and use a SwingWorker), if it takes too long monitor invokes a new window with progress bar and notification about the progress. Problem is that this window is focused on and I would rather like it to be opened in background, so the user can still browse files (the program is a simple file manager).


Solution

  • ProgressMonitor(parentComponent, message, note, min, max)

    Where:

    parentComponent - the parent component for the dialog box

    The dialog will have focus when it is visible, then should return focus to the parent when dismissed or set invisible.