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:com.mirth.connect.client.ui.SettingsPanelDatabaseTasks.java

public void doRunDatabaseTask() {
    DatabaseTask databaseTask = (DatabaseTask) taskTable.getValueAt(taskTable.getSelectedRow(), 1);

    if (databaseTask.getConfirmationMessage() != null
            && !getFrame().alertOption(getFrame(), databaseTask.getConfirmationMessage())) {
        return;//  w  ww .  j ava 2 s  .c  o  m
    }

    final String workingId = getFrame().startWorking("Running database task...");
    final String taskId = databaseTask.getId();

    SwingWorker<String, Void> worker = new SwingWorker<String, Void>() {

        @Override
        public String doInBackground() throws ClientException {
            return getFrame().mirthClient.runDatabaseTask(taskId);
        }

        @Override
        public void done() {
            try {
                String result = get();
                if (StringUtils.isNotBlank(result)) {
                    getFrame().alertInformation(getFrame(), result);
                }
            } catch (Throwable t) {
                if (t instanceof ExecutionException) {
                    t = t.getCause();
                }
                getFrame().alertThrowable(getFrame(), t, "Error running database task: " + t.getMessage());
            } finally {
                getFrame().stopWorking(workingId);
                doRefresh();
            }
        }
    };

    worker.execute();
    doRefresh();
}

From source file:com.anrisoftware.prefdialog.dialogaction.AbstractDialogAction.java

/**
 * Waits for the dialog to be created and opens the dialog. Waits until the
 * user either canceled or approved the dialog. After the dialog was
 * approved a value is created and returned.
 *
 * @see #createValue(SimpleDialog)/*  w ww . j  a  v a 2 s .co  m*/
 */
@Override
public ValueType call() throws Exception {
    worker = new SwingWorker<ValueType, Runnable>() {

        @Override
        protected ValueType doInBackground() throws Exception {
            publish(openDialog);
            waitForDialog();
            return createValue();
        }

        @Override
        protected void process(List<Runnable> chunks) {
            for (Runnable runnable : chunks) {
                runnable.run();
            }
        }

    };
    worker.execute();
    return worker.get();
}

From source file:edu.ku.brc.specify.plugins.ipadexporter.VerifyCollectionDlg.java

@SuppressWarnings({ "unchecked" })
@Override// ww w . j ava 2s.c  om
public void createUI() {
    loadAndPushResourceBundle(iPadDBExporterPlugin.RESOURCE_NAME);
    setTitle(getResourceString("VERIFY_TITLE"));
    try {
        htmlPane = new JEditorPane("text/html", ""); //$NON-NLS-1$
        final JScrollPane scrollPane = UIHelper.createScrollPane(htmlPane);
        //this.add(scrollPane, BorderLayout.CENTER);
        htmlPane.setEditable(false);

        CellConstraints cc = new CellConstraints();
        PanelBuilder pb = new PanelBuilder(new FormLayout("f:700px:g", "f:500px:g"));
        contentPanel = pb.getPanel();

        pb.add(scrollPane, cc.xy(1, 1));
        pb.setDefaultDialogBorder();

        setOkLabel("Continue");
        setCancelLabel("Close");
        setHelpLabel("To Browser");

        worker = new SwingWorker<Integer, Integer>() {
            @Override
            protected Integer doInBackground() throws Exception {
                processResults();
                return 0;
            }

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

                popResourceBundle();
            }
        };
        //addProgressListener(worker);
        worker.execute();

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        popResourceBundle();
    }

    setSize(800, 650);
    setBounds(0, 0, 650, 650);
    super.createUI();
    okBtn.setEnabled(false);
    setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); // Must be called at the end 'createUI'
}

From source file:com.mirth.connect.manager.ManagerController.java

public void startMirthWorker() {
    PlatformUI.MANAGER_DIALOG.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    ManagerController.getInstance().setEnabledOptions(false, false, false, false);

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        private String errorMessage = null;

        public Void doInBackground() {
            errorMessage = startMirth();
            return null;
        }/*w ww  . ja v a2 s .  com*/

        public void done() {
            if (errorMessage == null) {
                PlatformUI.MANAGER_TRAY.alertInfo("The Mirth Connect Service was started successfully.");
            } else {
                PlatformUI.MANAGER_TRAY.alertError(errorMessage);
            }

            updateMirthServiceStatus();
            PlatformUI.MANAGER_DIALOG.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
    };

    worker.execute();
}

From source file:com.mirth.connect.client.ui.LibraryResourcesDialog.java

public LibraryResourcesDialog(Channel channel) {
    super(PlatformUI.MIRTH_FRAME, true);

    selectedResourceIds = new HashMap<Integer, Set<String>>();

    Set<String> channelResourceIds = channel.getProperties().getResourceIds();
    if (channelResourceIds == null) {
        channelResourceIds = new LinkedHashSet<String>();
    }//from  w w w.  j  a  v  a2 s  .c om
    selectedResourceIds.put(null, new LinkedHashSet<String>(channelResourceIds));

    Set<String> sourceResourceIds = ((SourceConnectorPropertiesInterface) channel.getSourceConnector()
            .getProperties()).getSourceConnectorProperties().getResourceIds();
    if (sourceResourceIds == null) {
        sourceResourceIds = new LinkedHashSet<String>();
    }
    selectedResourceIds.put(channel.getSourceConnector().getMetaDataId(),
            new LinkedHashSet<String>(sourceResourceIds));

    for (Connector destinationConnector : channel.getDestinationConnectors()) {
        Set<String> destinationResourceIds = ((DestinationConnectorPropertiesInterface) destinationConnector
                .getProperties()).getDestinationConnectorProperties().getResourceIds();
        if (destinationResourceIds == null) {
            destinationResourceIds = new LinkedHashSet<String>();
        }
        selectedResourceIds.put(destinationConnector.getMetaDataId(),
                new LinkedHashSet<String>(destinationResourceIds));
    }

    initComponents(channel);
    setPreferredSize(new Dimension(450, 444));
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setTitle("Library Resources");
    pack();
    setLocationRelativeTo(PlatformUI.MIRTH_FRAME);

    okButton.setEnabled(false);
    final String workingId = PlatformUI.MIRTH_FRAME.startWorking("Loading library resources...");

    SwingWorker<List<LibraryProperties>, Void> worker = new SwingWorker<List<LibraryProperties>, Void>() {

        @Override
        public List<LibraryProperties> doInBackground() throws ClientException {
            List<ResourceProperties> resourceProperties = PlatformUI.MIRTH_FRAME.mirthClient.getResources();
            List<LibraryProperties> libraryProperties = new ArrayList<LibraryProperties>();
            for (ResourceProperties resource : resourceProperties) {
                if (resource instanceof LibraryProperties) {
                    libraryProperties.add((LibraryProperties) resource);
                }
            }
            return libraryProperties;
        }

        @Override
        public void done() {
            try {
                List<LibraryProperties> resources = get();
                if (resources == null) {
                    resources = new ArrayList<LibraryProperties>();
                }

                Object[][] data = new Object[resources.size()][3];
                int i = 0;

                for (LibraryProperties properties : resources) {
                    data[i][SELECTED_COLUMN] = null;
                    data[i][PROPERTIES_COLUMN] = properties;
                    data[i][TYPE_COLUMN] = properties.getType();
                    i++;
                }

                ((RefreshTableModel) resourceTable.getModel()).refreshDataVector(data);

                treeTable.getSelectionModel().setSelectionInterval(0, 0);
                treeTable.getTreeSelectionModel().setSelectionPath(treeTable.getPathForRow(0));
                okButton.setEnabled(true);
            } catch (Throwable t) {
                if (t instanceof ExecutionException) {
                    t = t.getCause();
                }
                PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, t,
                        "Error loading library resources: " + t.toString());
            } finally {
                PlatformUI.MIRTH_FRAME.stopWorking(workingId);
            }
        }
    };

    worker.execute();

    setVisible(true);
}

From source file:PostTest.java

public PostTestFrame() {
    setTitle("PostTest");

    northPanel = new JPanel();
    add(northPanel, BorderLayout.NORTH);
    northPanel.setLayout(new GridLayout(0, 2));
    northPanel.add(new JLabel("Host: ", SwingConstants.TRAILING));
    final JTextField hostField = new JTextField();
    northPanel.add(hostField);/*  w  ww.java2  s . c o  m*/
    northPanel.add(new JLabel("Action: ", SwingConstants.TRAILING));
    final JTextField actionField = new JTextField();
    northPanel.add(actionField);
    for (int i = 1; i <= 8; i++)
        northPanel.add(new JTextField());

    final JTextArea result = new JTextArea(20, 40);
    add(new JScrollPane(result));

    JPanel southPanel = new JPanel();
    add(southPanel, BorderLayout.SOUTH);
    JButton addButton = new JButton("More");
    southPanel.add(addButton);
    addButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            northPanel.add(new JTextField());
            northPanel.add(new JTextField());
            pack();
        }
    });

    JButton getButton = new JButton("Get");
    southPanel.add(getButton);
    getButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            result.setText("");
            final Map<String, String> post = new HashMap<String, String>();
            for (int i = 4; i < northPanel.getComponentCount(); i += 2) {
                String name = ((JTextField) northPanel.getComponent(i)).getText();
                if (name.length() > 0) {
                    String value = ((JTextField) northPanel.getComponent(i + 1)).getText();
                    post.put(name, value);
                }
            }
            new SwingWorker<Void, Void>() {
                protected Void doInBackground() throws Exception {
                    try {
                        String urlString = hostField.getText() + "/" + actionField.getText();
                        result.setText(doPost(urlString, post));
                    } catch (IOException e) {
                        result.setText("" + e);
                    }
                    return null;
                }
            }.execute();
        }
    });

    pack();
}

From source file:ca.uviccscu.lp.server.main.ShutdownListener.java

@Override
public void windowClosing(WindowEvent e) {
    if (Shared.hashInProgress) {
        JOptionPane.showMessageDialog(null, "Closing not allowed - stop or finish hashing first!",
                "Hash in progress!", JOptionPane.WARNING_MESSAGE);
    } else {/*ww w  .j  a  v  a 2s  .com*/
        SwingWorker worker = new SwingWorker<Void, Void>() {

            @Override
            public Void doInBackground() {
                try {
                    int ans1 = JOptionPane.showConfirmDialog(null,
                            "Are you sure you want to shutdown? "
                                    + "Clients will switch to passive mode until restarted.",
                            "Confirmation", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                    if (ans1 == JOptionPane.OK_OPTION) {
                        l.debug("MainFrame window closing requested");
                        MainFrame.lockInterface();
                        MainFrame.setReportingActive();
                        MainFrame.updateTask("Shutting down", true);
                        MainFrame.updateProgressBar(0, 0, 0, "Shutting down settings manager!", true, true);
                        l.trace("Shutting down settings manager and saving session");
                        int ans2 = JOptionPane.showConfirmDialog(null, "Do you want to save the games list",
                                "Save confirmation", JOptionPane.OK_CANCEL_OPTION,
                                JOptionPane.QUESTION_MESSAGE);
                        if (ans2 == JOptionPane.OK_OPTION) {
                            SettingsManager.showSaveSettingsDialog();
                        }
                        SettingsManager.shutdown();
                        l.trace("OK");
                        l.trace("Stopping net manager");
                        MainFrame.updateProgressBar(0, 0, 0, "Shutting down net manager!", true, true);
                        ServerNetManager.shutdown();
                        l.trace("OK");
                        l.trace("Shutting down tracker manager - might have errors here!");
                        MainFrame.updateProgressBar(0, 0, 0, "Shutting down azureus - might take a while!",
                                true, true);
                        //Errors due to Azureus stupid shutdown thread killing routine(see AzureusCoreImpl)
                        //Basically it kills all other threads it doesnt recognise on JVM and then terminates
                        //Not designed to work with other application, and so it also kills the shutdown thread = BAD
                        //Library modified to prevent system shutdown, but exceptions still coming - irrelevant
                        TrackerManager.shutdown();
                        Thread.yield();
                        l.trace("OK");
                        Thread.yield();
                        Thread.sleep(5000);
                        while (!Shared.azShutdownDone) {
                            try {
                                l.trace("Awaiting az shutdown");
                                Thread.sleep(500);
                            } catch (InterruptedException ex) {
                                l.error("Az shutdown monitor interrupted", ex);
                            }
                        }
                        MainFrame.updateProgressBar(0, 0, 0, "Cleaning temporary files - might take a while!",
                                true, true);
                        File f = new File(Shared.workingDirectory);
                        /*
                        //delete until files unlocked or timeout
                        if (!deleteFolder(f, true, 3000, 15000)) {
                        l.trace("Advanced file deletion measures required");
                        releaseLocks();
                        deleteFolder(f, false, 0, 0);
                        //Advanced thread killing, stolen from azureus...except now it kills itself
                        l.error("Delete timeout  - attempting threadicide");
                        l.trace("Starting thread killing");
                        //First kill azureus SM - allows to do whatever we want with threads
                        l.trace("Removed SM");
                        System.setSecurityManager(null);
                        //
                        ThreadGroup tg = Thread.currentThread().getThreadGroup();
                        while (tg.getParent() != null) {
                        tg = tg.getParent();
                        }
                        Thread[] threads = new Thread[tg.activeCount() + 1024];
                        tg.enumerate(threads, true);
                        //VERY BAD WAY TO STOP THREAD BUT NO CHOICE - need to release the file locks
                        for (int i = 0; i < threads.length; i++) {
                        Thread th = threads[i];
                        if (th != null && th != Thread.currentThread() && AEThread2.isOurThread(th)) {
                        l.trace("Stopping " + th.getName());
                        try {
                        th.stop();
                        l.trace("ok");
                        } catch (SecurityException e) {
                        l.trace("Stop vetoed by SM", e);
                        }
                                
                        }
                        }
                        //
                        deleteFolder(f, false, 0, 0);
                        l.error("Trying to stop more threads, list:");
                        //List remaining threads
                        ThreadGroup tg2 = Thread.currentThread().getThreadGroup();
                        while (tg2.getParent() != null) {
                        tg2 = tg2.getParent();
                        }
                        //Object o = new Object();
                        //o.notifyAll();
                        Thread[] threads2 = new Thread[tg2.activeCount() + 1024];
                        tg2.enumerate(threads2, true);
                        //VERY BAD WAY TO STOP THREAD BUT NO CHOICE - need to release the file locks
                        for (int i = 0; i < threads2.length; i++) {
                        Thread th = threads2[i];
                        if (th != null) {
                        l.trace("Have thread: " + th.getName());
                        if (th != null && th != Thread.currentThread() && (AEThread2.isOurThread(th) || isAzThread(th))) {
                        l.trace("Stopping " + th.getName());
                        try {
                        th.stop();
                        l.trace("ok");
                        } catch (SecurityException e) {
                        l.trace("Stop vetoed by SM", e);
                        }
                                
                        }
                        }
                        }
                        try {
                        Utils.cleanupDir();
                        l.trace("OK");
                        } catch (IOException e) {
                        l.trace("Cleaning failed after more thread cleanup", e);
                        Thread.yield();
                        }
                        threadCleanup(f);
                        l.error("Last resort - scheduling delete on JVM exit - might FAIL, CHECK MANUALLY");
                        try {
                        FileUtils.forceDeleteOnExit(f);
                        } catch (IOException iOException) {
                        l.fatal("All delete attempts failed - clean manually");
                        }
                        }
                        File test = new File("C:\\AZTest\\AZ\\logs\\debug_1.log");
                        test.deleteOnExit();
                        try {
                        Thread.sleep(30000);
                        } catch (InterruptedException ex) {
                        java.util.logging.Logger.getLogger(ShutdownListener.class.getName()).log(Level.SEVERE, null, ex);
                        }
                         *
                         */
                        threadReadout();
                        try {
                            Utils.cleanupDir();
                            l.trace("OK");
                        } catch (IOException e) {
                            l.trace("Cleaning failed - expected due to stupid Azureus file lock", e);
                            Thread.yield();
                        }
                        System.exit(0);
                        return null;
                    } else {
                        return null;
                    }
                } catch (Exception ex) {
                    l.fatal("Exception during shutdown!!!", ex);
                    //just end it
                    System.exit(4);
                    return null;
                }
            }
        };
        worker.execute();
    }
}

From source file:coreferenceresolver.gui.MarkupGUI.java

public MarkupGUI() throws IOException {
    highlightPainters = new ArrayList<>();

    for (int i = 0; i < COLORS.length; ++i) {
        DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(
                COLORS[i]);//w  w w.j  ava 2  s  .c  o  m
        highlightPainters.add(highlightPainter);
    }

    defaulPath = FileUtils.readFileToString(new File(".\\src\\coreferenceresolver\\gui\\defaultpath"));
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new BorderLayout());
    this.setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());

    JMenuBar menuBar = new JMenuBar();
    JMenu fileMenu = new JMenu("File");
    //create menu items
    JMenuItem importMenuItem = new JMenuItem("Import");

    JMenuItem exportMenuItem = new JMenuItem("Export");

    fileMenu.add(importMenuItem);
    fileMenu.add(exportMenuItem);

    menuBar.add(fileMenu);

    this.setJMenuBar(menuBar);

    ScrollablePanel mainPanel = new ScrollablePanel();
    mainPanel.setScrollableWidth(ScrollablePanel.ScrollableSizeHint.NONE);
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

    //IMPORT BUTTON
    importMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //                MarkupGUI.reviewElements.clear();
            //                MarkupGUI.markupReviews.clear();                
            JFileChooser markupFileChooser = new JFileChooser(defaulPath);
            markupFileChooser.setDialogTitle("Choose your markup file");
            markupFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

            if (markupFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                final JDialog d = new JDialog();
                JPanel p1 = new JPanel(new GridBagLayout());
                p1.add(new JLabel("Please Wait..."), new GridBagConstraints());
                d.getContentPane().add(p1);
                d.setSize(100, 100);
                d.setLocationRelativeTo(null);
                d.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                d.setModal(true);

                SwingWorker<?, ?> worker = new SwingWorker<Void, Void>() {
                    protected Void doInBackground() throws IOException, BadLocationException {
                        readMarkupFile(markupFileChooser.getSelectedFile().getAbsolutePath());
                        for (int i = 0; i < markupReviews.size(); ++i) {
                            mainPanel.add(newReviewPanel(markupReviews.get(i), i));
                        }
                        return null;
                    }

                    protected void done() {
                        MarkupGUI.this.revalidate();
                        d.dispose();
                    }
                };
                worker.execute();
                d.setVisible(true);
            } else {
                return;
            }
        }
    });

    //EXPORT BUTTON: GET NEW VALUE (REF, TYPE) OF NPs      
    exportMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser markupFileChooser = new JFileChooser(defaulPath);
            markupFileChooser.setDialogTitle("Choose where your markup file saved");
            markupFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

            if (markupFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                final JDialog d = new JDialog();
                JPanel p1 = new JPanel(new GridBagLayout());
                p1.add(new JLabel("Please Wait..."), new GridBagConstraints());
                d.getContentPane().add(p1);
                d.setSize(100, 100);
                d.setLocationRelativeTo(null);
                d.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                d.setModal(true);

                SwingWorker<?, ?> worker = new SwingWorker<Void, Void>() {
                    protected Void doInBackground() throws IOException {
                        for (Review review : markupReviews) {
                            generateNPsRef(review);
                        }
                        int i = 0;
                        for (ReviewElement reviewElement : reviewElements) {
                            int j = 0;
                            for (Element element : reviewElement.elements) {
                                String newType = element.typeSpinner.getValue().toString();
                                if (newType.equals("Object")) {
                                    markupReviews.get(i).getNounPhrases().get(j).setType(0);
                                } else if (newType.equals("Attribute")) {
                                    markupReviews.get(i).getNounPhrases().get(j).setType(3);
                                } else if (newType.equals("Other")) {
                                    markupReviews.get(i).getNounPhrases().get(j).setType(1);
                                } else if (newType.equals("Candidate")) {
                                    markupReviews.get(i).getNounPhrases().get(j).setType(2);
                                }
                                ++j;
                            }
                            ++i;
                        }
                        initMarkupFile(markupFileChooser.getSelectedFile().getAbsolutePath() + File.separator
                                + "markup.out.txt");
                        return null;
                    }

                    protected void done() {
                        d.dispose();
                        try {
                            Desktop.getDesktop()
                                    .open(new File(markupFileChooser.getSelectedFile().getAbsolutePath()));
                        } catch (IOException ex) {
                            Logger.getLogger(MarkupGUI.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                };
                worker.execute();
                d.setVisible(true);
            } else {
                return;
            }
        }
    });

    JScrollPane scrollMainPane = new JScrollPane(mainPanel);
    scrollMainPane.getVerticalScrollBar().setUnitIncrement(16);
    scrollMainPane.setPreferredSize(new Dimension(this.getWidth(), this.getHeight()));
    scrollMainPane.setSize(this.getWidth(), this.getHeight());
    this.setResizable(false);
    this.add(scrollMainPane, BorderLayout.CENTER);
    this.setExtendedState(JFrame.MAXIMIZED_BOTH);
    this.pack();
}

From source file:edu.ku.brc.specify.config.init.InstSetupPanel.java

/**
 * /*from   w w w. j  a  va2  s  .  c o m*/
 */
protected void doCreate() {
    if (isOK == null || !isOK) {
        progressBar.setIndeterminate(true);
        progressBar.setVisible(true);

        setUIEnabled(false);

        label.setText(UIRegistry.getResourceString("CONN_DB"));

        testBtn.setVisible(false);

        SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
            @Override
            protected Object doInBackground() throws Exception {
                isOK = false;
                try {
                    getValues(properties);

                    firePropertyChange(propName, 0, 1);

                    conn = DBConnection.getInstance();

                    AppContextMgr.getInstance().setHasContext(true); // override

                    BuildSampleDatabase bsd = new BuildSampleDatabase();

                    bsd.setSession(HibernateUtil.getCurrentSession());

                    int treeDir = BuildSampleDatabase.getTreeDirForClass(properties, StorageTreeDef.class);

                    isOK = bsd.createEmptyInstitution(properties, false, false, true, treeDir);

                    AppContextMgr.getInstance().setClassObject(DataType.class, bsd.getDataType());

                    HibernateUtil.closeSession();

                    if (!isOK) {
                        errorKey = "BAD_INST";
                        return null;
                    }

                    String userName = properties.getProperty("usrUsername");
                    String password = properties.getProperty("usrPassword");
                    String dbName = properties.getProperty("dbName");

                    firePropertyChange(propName, 0, 2);

                    isOK = tryLogginIn(userName, password, dbName);
                    if (!isOK) {
                        errorKey = "BAD_LOGIN";
                        return null;
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();

                    errorKey = "INST_UNRECOVERABLE";
                }

                return null;
            }

            /* (non-Javadoc)
             * @see javax.swing.SwingWorker#done()
             */
            @Override
            protected void done() {
                super.done();

                progressBar.setIndeterminate(false);
                progressBar.setVisible(false);

                setUIEnabled(true);

                updateBtnUI();

                label.setText(UIRegistry.getResourceString(
                        isOK ? "INST_CREATED" : (errorKey != null ? errorKey : "ERR_CRE_INST")));

                if (isOK) {
                    setUIEnabled(false);
                    prevBtn.setEnabled(false);
                }
            }
        };

        worker.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(final PropertyChangeEvent evt) {
                if (propName.equals(evt.getPropertyName())) {
                    String key = null;
                    switch ((Integer) evt.getNewValue()) {
                    case 1:
                        key = "CREATING_INST";
                        break;
                    case 2:
                        key = "LOGIN_USER";
                        break;
                    default:
                        break;
                    }
                    if (key != null) {
                        InstSetupPanel.this.label.setText(UIRegistry.getResourceString(key));
                    }
                }
            }
        });
        worker.execute();
    }
}

From source file:net.sourceforge.atunes.kernel.actions.RemoveFromDiskAction.java

private void fromRepositoryOrDeviceView() {
    TreePath[] paths = NavigationHandler.getInstance().getCurrentView().getTree().getSelectionPaths();
    final List<Folder> foldersToRemove = new ArrayList<Folder>();
    if (paths != null) {
        for (TreePath path : paths) {
            Object treeNode = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject();
            if (treeNode instanceof Folder) {
                foldersToRemove.add((Folder) treeNode);
            }/*from ww w . j  a  va2 s .c  o m*/
        }
    }
    RepositoryHandler.getInstance().removeFolders(foldersToRemove);
    VisualHandler.getInstance().showIndeterminateProgressDialog(LanguageTool.getString("PLEASE_WAIT"));
    new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() {
            for (Folder folder : foldersToRemove) {
                try {
                    FileUtils.deleteDirectory(folder.getFolderPath());
                    logger.info(LogCategories.REPOSITORY, StringUtils.getString("Removed folder ", folder));
                } catch (IOException e) {
                    logger.info(LogCategories.REPOSITORY,
                            StringUtils.getString("Could not remove folder ", folder, e.getMessage()));
                }
            }
            return null;
        }

        @Override
        protected void done() {
            VisualHandler.getInstance().hideIndeterminateProgressDialog();
        }
    }.execute();
}