Example usage for javax.swing SwingWorker SwingWorker

List of usage examples for javax.swing SwingWorker SwingWorker

Introduction

In this page you can find the example usage for javax.swing SwingWorker SwingWorker.

Prototype

public SwingWorker() 

Source Link

Document

Constructs this SwingWorker .

Usage

From source file:org.kuali.test.ui.components.sqlquerypanel.DatabasePanel.java

@Override
protected void initComponents() {
    super.initComponents();

    JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));

    p.add(new JLabel("Base Table:", JLabel.RIGHT));
    p.add(tableDropdown = new JComboBox());

    p.add(spinner = new Spinner("Loading available database tables..."));

    new SwingWorker() {
        @Override// w  w w  . java 2 s . c  o m
        protected Object doInBackground() throws Exception {
            loadAvailableDatabaseTables();
            return null;
        };

        @Override
        protected void done() {
            spinner.stopSpinner();
            tableDropdown.addActionListener(DatabasePanel.this);
        }
    }.execute();

    JPanel p2 = new JPanel(new BorderLayout());
    p2.add(p, BorderLayout.NORTH);

    tabbedPane = new JTabbedPane();
    tabbedPane.addTab("Columns",
            new JScrollPane(sqlQueryTree = new SqlQueryTree(getMainframe(), this, getPlatform())));
    tabbedPane.addTab("Select", sqlSelectPanel = new SqlSelectPanel(getMainframe(), this));
    tabbedPane.addTab("Where", sqlWherePanel = new SqlWherePanel(getMainframe(), this));
    tabbedPane.addTab("SQL", sqlDisplayPanel = new SqlDisplayPanel(getMainframe(), this));

    p2.add(tabbedPane, BorderLayout.CENTER);

    add(p2, BorderLayout.CENTER);

    if (!forCheckpoint) {
        getMainframe().getCreateTestButton().setEnabled(false);
        getMainframe().getCreateTestMenuItem().setEnabled(false);
    }
}

From source file:org.kuali.test.ui.components.sqlquerypanel.DatabasePanel.java

/**
 *
 * @param e/*from  w  ww  .j  a  va2  s  . com*/
 */
@Override
protected void handleUnprocessedActionEvent(ActionEvent e) {
    if (e.getSource() == tableDropdown) {
        final TableData td = (TableData) tableDropdown.getSelectedItem();

        if (StringUtils.isNotBlank(td.getName())) {

            spinner.startSpinner("Loading table relationships...");
            new SwingWorker() {
                @Override
                protected Object doInBackground() throws Exception {
                    Object retval = null;
                    try {
                        DefaultMutableTreeNode rootNode = sqlQueryTree.getRootNode();
                        rootNode.removeAllChildren();
                        loadTables(td, rootNode);
                    }

                    catch (Exception ex) {
                        retval = ex.toString();
                    }
                    return retval;
                };

                @Override
                protected void done() {
                    spinner.stopSpinner();
                    try {
                        Object result = get();

                        if (result != null) {
                            UIUtils.showError(getMainframe(), "Error loading table relationships",
                                    "An error occured while loading table relationships - "
                                            + result.toString());
                        } else {
                            DefaultMutableTreeNode rootNode = sqlQueryTree.getRootNode();
                            sqlQueryTree.getModel().nodeStructureChanged(rootNode);
                            sqlQueryTree.expandNode(rootNode, 1);
                            sqlSelectPanel.clear();
                            sqlWherePanel.clear();
                        }
                    }

                    catch (Exception ex) {
                        LOG.error(ex.toString(), ex);
                    }
                }
            }.execute();
        }
    }
}

From source file:org.n52.ifgicopter.spf.gui.SPFMainFrame.java

protected void shutdownFrame(final int returnCode) {
    SwingWorker<String, Object> worker = new SwingWorker<String, Object>() {

        @Override//w ww.j  a v  a 2 s  . c  o m
        protected String doInBackground() throws Exception {
            SPFMainFrame.this.statusLabel.setText("SPFramework shutting down... this could take a while.");

            ShutdownDialog dialog = new ShutdownDialog(SPFMainFrame.this);
            new Thread(dialog).start();

            try {
                SPFRegistry.getInstance().shutdownSystem();
            } catch (Exception e1) {
                SPFMainFrame.this.log.warn(e1.getMessage(), e1);

                //check if we have a restart returnCode, then do not error
                if (returnCode == 0)
                    System.exit(1);
            } finally {
                System.exit(returnCode);
            }

            return null;
        }
    };

    worker.execute();
}

From source file:org.omegat.gui.align.AlignPanelController.java

/**
 * Reloads the beads with the current settings. The loading itself takes place on a background thread.
 * Calls {@link #updatePanel(AlignPanel, AlignMenuFrame)} afterwards.
 * /*from   w w  w. jav a2  s  .c o m*/
 * @param panel
 * @param frame
 */
private void reloadBeads() {
    if (loader != null) {
        loader.cancel(true);
    }
    phase = Phase.ALIGN;
    panel.progressBar.setVisible(true);
    panel.continueButton.setEnabled(false);
    panel.controlsPanel.setVisible(false);
    loader = new SwingWorker<List<MutableBead>, Object>() {
        @Override
        protected List<MutableBead> doInBackground() throws Exception {
            return aligner.alignImpl().filter(o -> !isCancelled()).map(MutableBead::new)
                    .collect(Collectors.toList());
        }

        @Override
        protected void done() {
            List<MutableBead> beads = null;
            try {
                beads = get();
            } catch (CancellationException ex) {
                // Ignore
            } catch (Exception e) {
                Log.log(e);
                JOptionPane.showMessageDialog(panel, OStrings.getString("ALIGNER_ERROR_LOADING"),
                        OStrings.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE);
            }
            panel.continueButton.setEnabled(true);
            panel.progressBar.setVisible(false);
            panel.comparisonComboBox
                    .setModel(new DefaultComboBoxModel<>(aligner.allowedModes.toArray(new ComparisonMode[0])));

            String distanceValue = null;
            if (beads != null) {
                double avgDist = MutableBead.calculateAvgDist(beads);
                distanceValue = StringUtil.format(OStrings.getString("ALIGNER_PANEL_LABEL_AVGSCORE"),
                        avgDist == Long.MAX_VALUE ? "-" : String.format("%.3f", avgDist));
                panel.table.setModel(new BeadTableModel(beads));
                for (int i = 0; i < BeadTableModel.COL_SRC; i++) {
                    TableColumn col = panel.table.getColumnModel().getColumn(i);
                    col.setMaxWidth(col.getWidth());
                }
                modified = false;
            }
            panel.averageDistanceLabel.setText(distanceValue);

            updatePanel();
        }
    };
    loader.execute();
}

From source file:org.omegat.gui.dialogs.LogDialog.java

/**
 * Creates new form LogDialog// w w  w .  j a  va 2  s  .c o  m
 */
public LogDialog(java.awt.Frame parent) {
    super(parent, true);
    initComponents();

    setTitle(OStrings.getString("LOGDIALOG_TITLE") + " " + Log.getLogFileName());

    StaticUIUtils.setEscapeClosable(this);

    setSize(600, 400);
    setLocationRelativeTo(parent);

    final File logLocation = new File(Log.getLogFilePath());
    new SwingWorker<String, Object>() {
        @Override
        protected String doInBackground() throws Exception {
            try (FileInputStream fis = new FileInputStream(logLocation)) {
                return IOUtils.toString(fis, StandardCharsets.UTF_8);
            } catch (Exception e) {
                return "";
            }
        }

        protected void done() {
            try {
                logTextPane.setText(get());
            } catch (Exception e) {
                Log.log(e);
            }
            logTextPane.setCaretPosition(0);
            OSXIntegration.setProxyIcon(getRootPane(), logLocation);
        };
    }.execute();
}

From source file:org.omegat.gui.main.ProjectUICommands.java

public static void projectCreate() {
    UIThreadsUtil.mustBeSwingThread();//w  ww .ja  v  a  2s.co m

    if (Core.getProject().isProjectLoaded()) {
        return;
    }

    // ask for new project dir
    NewProjectFileChooser ndc = new NewProjectFileChooser();
    int ndcResult = ndc.showSaveDialog(Core.getMainWindow().getApplicationFrame());
    if (ndcResult != OmegaTFileChooser.APPROVE_OPTION) {
        // user press 'Cancel' in project creation dialog
        return;
    }
    final File dir = ndc.getSelectedFile();

    new SwingWorker<Object, Void>() {
        protected Object doInBackground() throws Exception {

            dir.mkdirs();

            // ask about new project properties
            ProjectProperties props = new ProjectProperties(dir);
            props.setSourceLanguage(Preferences.getPreferenceDefault(Preferences.SOURCE_LOCALE, "EN-US"));
            props.setTargetLanguage(Preferences.getPreferenceDefault(Preferences.TARGET_LOCALE, "EN-GB"));
            ProjectPropertiesDialog newProjDialog = new ProjectPropertiesDialog(
                    Core.getMainWindow().getApplicationFrame(), props, dir.getAbsolutePath(),
                    ProjectPropertiesDialog.Mode.NEW_PROJECT);
            newProjDialog.setVisible(true);
            newProjDialog.dispose();

            IMainWindow mainWindow = Core.getMainWindow();
            Cursor hourglassCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
            Cursor oldCursor = mainWindow.getCursor();
            mainWindow.setCursor(hourglassCursor);

            final ProjectProperties newProps = newProjDialog.getResult();
            if (newProps == null) {
                // user clicks on 'Cancel'
                dir.delete();
                mainWindow.setCursor(oldCursor);
                return null;
            }

            final String projectRoot = newProps.getProjectRoot();

            if (!StringUtil.isEmpty(projectRoot)) {
                // create project
                try {
                    ProjectFactory.createProject(newProps);
                } catch (Exception ex) {
                    Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
                    Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
                }
            }

            RecentProjects.add(dir.getAbsolutePath());

            mainWindow.setCursor(oldCursor);
            return null;
        }
    }.execute();
}

From source file:org.omegat.gui.main.ProjectUICommands.java

public static void projectOpenMED() {
    UIThreadsUtil.mustBeSwingThread();/*from  w w  w.  j a v  a2  s .  c  om*/

    if (Core.getProject().isProjectLoaded()) {
        return;
    }

    // ask for MED file
    ChooseMedProject ndm = new ChooseMedProject();
    int ndmResult = ndm.showOpenDialog(Core.getMainWindow().getApplicationFrame());
    if (ndmResult != OmegaTFileChooser.APPROVE_OPTION) {
        // user press 'Cancel' in project creation dialog
        return;
    }
    final File med = ndm.getSelectedFile();

    // ask for new project dir
    NewProjectFileChooser ndc = new NewProjectFileChooser();
    int ndcResult = ndc.showSaveDialog(Core.getMainWindow().getApplicationFrame());
    if (ndcResult != OmegaTFileChooser.APPROVE_OPTION) {
        // user press 'Cancel' in project creation dialog
        return;
    }
    final File dir = ndc.getSelectedFile();

    new SwingWorker<Object, Void>() {
        protected Object doInBackground() throws Exception {
            dir.mkdirs();

            final ProjectProperties newProps = new ProjectProperties(dir);
            ProjectMedProcessing.extractFromMed(med, newProps);
            // create project
            try {
                ProjectFactory.createProject(newProps);
            } catch (Exception ex) {
                Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
                Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
            }

            RecentProjects.add(dir.getAbsolutePath());

            return null;
        }

        protected void done() {
            try {
                get();
                SwingUtilities.invokeLater(Core.getEditor()::requestFocus);
            } catch (Exception ex) {
                Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
                Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
            }
        }
    }.execute();
}

From source file:org.omegat.gui.main.ProjectUICommands.java

public static void projectCreateMED() {
    UIThreadsUtil.mustBeSwingThread();/*from   w  w  w  . jav a  2  s  . c  o  m*/

    if (!Core.getProject().isProjectLoaded()) {
        return;
    }

    // commit the current entry first
    Core.getEditor().commitAndLeave();

    // ask for new MED file
    ChooseMedProject ndm = new ChooseMedProject();
    // default name
    String zipName = null;
    try {
        File origin = ProjectMedProcessing.getOriginMedFile(Core.getProject().getProjectProperties());
        if (origin != null) {
            zipName = origin.getName();
        }
    } catch (Exception ex) {
    }
    if (zipName == null) {
        zipName = Core.getProject().getProjectProperties().getProjectName() + "-MED.zip";
    }
    ndm.setSelectedFile(
            new File(Core.getProject().getProjectProperties().getProjectRootDir().getParentFile(), zipName));
    int ndmResult = ndm.showSaveDialog(Core.getMainWindow().getApplicationFrame());
    if (ndmResult != OmegaTFileChooser.APPROVE_OPTION) {
        // user press 'Cancel' in project creation dialog
        return;
    }
    // add .zip extension if there is no
    final File med = ndm.getSelectedFile().getName().toLowerCase().endsWith(".zip") ? ndm.getSelectedFile()
            : new File(ndm.getSelectedFile().getAbsolutePath() + ".zip");

    new SwingWorker<Object, Void>() {
        protected Object doInBackground() throws Exception {
            IMainWindow mainWindow = Core.getMainWindow();
            Cursor hourglassCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
            Cursor oldCursor = mainWindow.getCursor();
            mainWindow.setCursor(hourglassCursor);

            mainWindow.showStatusMessageRB("MW_STATUS_SAVING");

            Core.executeExclusively(true, () -> {
                Core.getProject().saveProject(true);
                try {
                    Core.getProject().compileProject(".*");
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            });

            ProjectMedProcessing.createMed(med, Core.getProject().getProjectProperties());

            mainWindow.showStatusMessageRB("MW_STATUS_SAVED");
            mainWindow.setCursor(oldCursor);
            return null;
        }

        protected void done() {
            try {
                get();
                SwingUtilities.invokeLater(Core.getEditor()::requestFocus);
            } catch (Exception ex) {
                Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
                Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
            }
        }
    }.execute();
}

From source file:org.omegat.gui.main.ProjectUICommands.java

public static void projectTeamCreate() {
    UIThreadsUtil.mustBeSwingThread();//from  ww  w  .  jav  a2 s.c  o  m

    if (Core.getProject().isProjectLoaded()) {
        return;
    }
    new SwingWorker<Object, Void>() {
        File projectRoot;

        protected Object doInBackground() throws Exception {
            Core.getMainWindow().showStatusMessageRB(null);

            final NewTeamProject dialog = new NewTeamProject(Core.getMainWindow().getApplicationFrame());
            dialog.setVisible(true);

            if (!dialog.ok) {
                Core.getMainWindow().showStatusMessageRB("TEAM_CANCELLED");
                return null;
            }

            IMainWindow mainWindow = Core.getMainWindow();
            Cursor hourglassCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
            Cursor oldCursor = mainWindow.getCursor();
            mainWindow.setCursor(hourglassCursor);
            Core.getMainWindow().showStatusMessageRB("CT_DOWNLOADING_PROJECT");

            // retrieve omegat.project
            projectRoot = new File(dialog.getSaveLocation());
            List<RepositoryDefinition> repos = new ArrayList<RepositoryDefinition>();
            RepositoryDefinition repo = new RepositoryDefinition();
            repos.add(repo);
            repo.setType(dialog.getRepoType());
            repo.setUrl(dialog.getRepoUrl());
            RepositoryMapping mapping = new RepositoryMapping();
            mapping.setLocal("");
            mapping.setRepository("");
            repo.getMapping().add(mapping);

            RemoteRepositoryProvider remoteRepositoryProvider = new RemoteRepositoryProvider(projectRoot,
                    repos);
            remoteRepositoryProvider.switchAllToLatest();
            for (String file : new String[] { OConsts.FILE_PROJECT,
                    OConsts.DEFAULT_INTERNAL + '/' + FilterMaster.FILE_FILTERS,
                    OConsts.DEFAULT_INTERNAL + '/' + SRX.CONF_SENTSEG }) {
                remoteRepositoryProvider.copyFilesFromRepoToProject(file);
            }

            // update repo into
            ProjectProperties props = ProjectFileStorage.loadProjectProperties(projectRoot);
            props.setRepositories(repos);
            ProjectFileStorage.writeProjectFile(props);

            //String projectFileURL = dialog.txtRepositoryOrProjectFileURL.getText();
            //File localDirectory = new File(dialog.txtDirectory.getText());
            //                try {
            //                    localDirectory.mkdirs();
            //                    byte[] projectFile = WikiGet.getURLasByteArray(projectFileURL);
            //                    FileUtils.writeByteArrayToFile(new File(localDirectory, OConsts.FILE_PROJECT), projectFile);
            //                } catch (Exception ex) {
            //                    ex.printStackTrace();
            //                    Core.getMainWindow().displayErrorRB(ex, "TEAM_CHECKOUT_ERROR");
            //                    mainWindow.setCursor(oldCursor);
            //                    return null;
            //                }

            //                projectOpen(localDirectory);

            mainWindow.setCursor(oldCursor);
            return null;
        }

        @Override
        protected void done() {
            Core.getMainWindow().showProgressMessage(" ");
            try {
                get();
                if (projectRoot != null) {
                    // don't ask open if user cancelled previous dialog
                    SwingUtilities.invokeLater(() -> {
                        Core.getEditor().requestFocus();
                        projectOpen(projectRoot);
                    });

                }
            } catch (Exception ex) {
                Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_DOWNLOAD_TEAM_PROJECT");
                Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_DOWNLOAD_TEAM_PROJECT");
            }
        }
    }.execute();
}

From source file:org.omegat.gui.main.ProjectUICommands.java

/**
 * Open project. Does nothing if a project is already open and closeCurrent is false.
 * /*  ww w .  j av a  2s  .c  o  m*/
 * @param projectDirectory
 *            project directory or null if user must choose it
 * @param closeCurrent
 *            whether or not to close the current project first, if any
 */
public static void projectOpen(final File projectDirectory, boolean closeCurrent) {
    UIThreadsUtil.mustBeSwingThread();

    if (Core.getProject().isProjectLoaded()) {
        if (closeCurrent) {
            // Register to try again after closing the current project.
            CoreEvents.registerProjectChangeListener(new IProjectEventListener() {
                public void onProjectChanged(PROJECT_CHANGE_TYPE eventType) {
                    if (eventType == PROJECT_CHANGE_TYPE.CLOSE) {
                        projectOpen(projectDirectory, false);
                        CoreEvents.unregisterProjectChangeListener(this);
                    }
                }
            });
            projectClose();
        }
        return;
    }

    final File projectRootFolder;
    if (projectDirectory == null) {
        // select existing project file - open it
        OmegaTFileChooser pfc = new OpenProjectFileChooser();
        if (OmegaTFileChooser.APPROVE_OPTION != pfc
                .showOpenDialog(Core.getMainWindow().getApplicationFrame())) {
            return;
        }
        projectRootFolder = pfc.getSelectedFile();
    } else {
        projectRootFolder = projectDirectory;
    }

    new SwingWorker<Object, Void>() {
        protected Object doInBackground() throws Exception {

            IMainWindow mainWindow = Core.getMainWindow();
            Cursor hourglassCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
            Cursor oldCursor = mainWindow.getCursor();
            mainWindow.setCursor(hourglassCursor);

            try {
                // convert old projects if need
                ConvertProject.convert(projectRootFolder);
            } catch (Exception ex) {
                Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_CONVERT_PROJECT");
                Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_CONVERT_PROJECT");
                mainWindow.setCursor(oldCursor);
                return null;
            }

            // check if project okay
            ProjectProperties props;
            try {
                props = ProjectFileStorage.loadProjectProperties(projectRootFolder.getAbsoluteFile());
            } catch (Exception ex) {
                Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
                Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
                mainWindow.setCursor(oldCursor);
                return null;
            }

            try {
                boolean needToSaveProperties = false;
                if (props.hasRepositories()) {
                    // team project - non-exist directories could be created from repo
                    props.autocreateDirectories();
                } else {
                    // not a team project - ask for non-exist directories
                    while (!props.isProjectValid()) {
                        needToSaveProperties = true;
                        // something wrong with the project - display open dialog
                        // to fix it
                        ProjectPropertiesDialog prj = new ProjectPropertiesDialog(
                                Core.getMainWindow().getApplicationFrame(), props,
                                new File(projectRootFolder, OConsts.FILE_PROJECT).getAbsolutePath(),
                                ProjectPropertiesDialog.Mode.RESOLVE_DIRS);
                        prj.setVisible(true);
                        props = prj.getResult();
                        prj.dispose();
                        if (props == null) {
                            // user clicks on 'Cancel'
                            mainWindow.setCursor(oldCursor);
                            return null;
                        }
                    }
                }

                final ProjectProperties propsP = props;
                Core.executeExclusively(true, () -> ProjectFactory.loadProject(propsP, true));
                if (needToSaveProperties) {
                    Core.getProject().saveProjectProperties();
                }
            } catch (Exception ex) {
                Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
                Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
                mainWindow.setCursor(oldCursor);
                return null;
            }

            RecentProjects.add(projectRootFolder.getAbsolutePath());

            mainWindow.setCursor(oldCursor);
            return null;
        }

        protected void done() {
            try {
                get();
                SwingUtilities.invokeLater(Core.getEditor()::requestFocus);
            } catch (Exception ex) {
                Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
                Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
            }
        }
    }.execute();
}