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.openconcerto.erp.core.finance.accounting.ui.EtatJournauxPanel.java

public void loadAsynchronous() {

    // On recupere les differents journaux
    SQLTable journalTable = base.getTable("JOURNAL");

    List<SQLRow> liste = SQLBackgroundTableCache.getInstance().getCacheForTable(journalTable).getRows();
    for (int k = 0; k < liste.size(); k++) {
        SQLRow row = liste.get(k);//from   w  w  w  .  jav a2 s .c o  m
        fireIsLoading(true);
        final Journal jrnlTmp = new Journal(row.getID(), row.getString("NOM"), row.getString("CODE"));
        new SwingWorker<JPanel, Object>() {
            @Override
            protected JPanel doInBackground() throws Exception {

                final JPanel initJournalPanel = initJournalPanel(jrnlTmp);
                return initJournalPanel;
            }

            @Override
            protected void done() {
                JPanel initJournalPanel;
                try {
                    initJournalPanel = get();

                    initJournalPanel.setOpaque(false);
                    JScrollPane scroll = new JScrollPane(initJournalPanel);
                    scroll.setBorder(null);
                    scroll.setOpaque(false);
                    scroll.getViewport().setOpaque(false);
                    EtatJournauxPanel.this.tabbedJournaux.addTab(jrnlTmp.getNom(), scroll);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                fireIsLoading(false);
                super.done();
            }
        }.execute();

    }
}

From source file:org.openconcerto.erp.core.finance.accounting.ui.GrandLivrePanel.java

public void loadAsynchronous() {
    // On recupere les differentes classes
    List<ClasseCompte> liste = ClasseCompte.getClasseCompte();

    if (liste.size() != 0) {
        for (int k = 0; k < liste.size(); k++) {

            final ClasseCompte ccTmp = liste.get(k);
            fireLoading(true);/*from   w ww  .  j  a  va 2s .  c o  m*/
            new SwingWorker<JPanel, Object>() {
                @Override
                protected JPanel doInBackground() throws Exception {
                    // TODO Auto-generated method stub
                    return initClassePanel(ccTmp);

                }

                @Override
                protected void done() {
                    JPanel initClassePanel;
                    try {
                        initClassePanel = get();

                        initClassePanel.setOpaque(false);

                        final JScrollPane scrollPane = new JScrollPane(initClassePanel);
                        scrollPane.setOpaque(false);
                        scrollPane.setBorder(null);
                        scrollPane.getViewport().setOpaque(false);
                        // On crer les comptes de chaque classe
                        GrandLivrePanel.this.tabbedClasse.addTab(ccTmp.getNom(), scrollPane);

                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    fireLoading(false);
                    super.done();
                }
            }.execute();

        }
    }
}

From source file:org.photovault.swingui.FindAddressAction.java

public void actionPerformed(ActionEvent e) {
    final String geoHashStr = (String) ctrl.getFieldController("shotLocation.geoHashString").getValue();
    SwingWorker<Location, Object> w = new SwingWorker<Location, Object>() {

        @Override//ww  w  .  ja  v  a  2s.  c  om
        protected Location doInBackground() throws Exception {
            return geocoder.findByGeoHash(geoHashStr);
        }

        @Override
        protected void done() {
            try {
                updateAddress(get());
            } catch (Exception ignore) {
            }
        }
    };
    w.execute();
}

From source file:org.pmedv.blackboard.commands.OpenBoardCommand.java

@Override
public void execute(ActionEvent e) {

    final ApplicationWindow win = ctx.getBean(ApplicationWindow.class);

    // No file selected before, popup a dialog and query the user which file to open.
    if (file == null) {
        String path = System.getProperty("user.home");
        if (AppContext.getLastSelectedFolder() != null) {
            path = AppContext.getLastSelectedFolder();
        }/*from   w  ww  . j a  va2 s  .c o m*/
        JFileChooser fc = new JFileChooser(path);
        fc.setDialogTitle(resources.getResourceByKey("OpenBoardCommand.name"));
        fc.setFileFilter(new FefaultFileFilter());
        int result = fc.showOpenDialog(win);
        if (result == JFileChooser.APPROVE_OPTION) {
            if (fc.getSelectedFile() == null)
                return;
            file = fc.getSelectedFile();
            AppContext.setLastSelectedFolder(file.getParentFile().getAbsolutePath());
        } else {
            return;
        }
    }

    final JWindow topWindow = new JWindow();
    topWindow.setSize(390, 50);
    topWindow.setLayout(new BorderLayout());
    topWindow.setBackground(Color.WHITE);

    final JPanel content = new JPanel(new BorderLayout());
    content.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK),
            BorderFactory.createEmptyBorder(10, 10, 10, 10)));
    content.setBackground(Color.WHITE);
    final JLabel infoLabel = new JLabel(
            resources.getResourceByKey("OpenBoardCommand.waitMsg") + " " + file.getName());
    infoLabel.setVerticalAlignment(SwingConstants.CENTER);
    content.add(infoLabel, BorderLayout.SOUTH);

    final JBusyComponent<JPanel> busyPanel = new JBusyComponent<JPanel>(content);
    busyPanel.setBusy(true);

    topWindow.getContentPane().add(busyPanel, BorderLayout.CENTER);
    topWindow.setLocationRelativeTo(null);
    topWindow.add(busyPanel, BorderLayout.CENTER);

    final SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>() {

        @Override
        protected Boolean doInBackground() {
            topWindow.setVisible(true);
            doOpen();
            return Boolean.valueOf(true);
        }

        @Override
        protected void done() {
            topWindow.setVisible(false);
            topWindow.dispose();
            for (Runnable r : postConfigurators) {
                SwingUtilities.invokeLater(r);
            }
        }
    };

    worker.execute();

}

From source file:org.pmedv.blackboard.components.PartView.java

protected void initializeComponents() {

    setLayout(new BorderLayout());

    partPanel = new PartPanel();
    partBusyPanel = new JBusyComponent<PartPanel>(partPanel);

    setSize(new Dimension(900, 650));

    textArea = new RSyntaxTextArea();
    textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_XML);
    RTextScrollPane textScrollPane = new RTextScrollPane(textArea);

    CompletionProvider provider = createCompletionProvider();
    AutoCompletion ac = new AutoCompletion(provider);
    ac.install(textArea);//from   ww w  .ja  v  a2  s  .co  m

    JPopupMenu popup = textArea.getPopupMenu();
    popup.addSeparator();
    popup.add(new JMenuItem(new SaveAction()));

    tabbedPane = new JTabbedPane(JTabbedPane.BOTTOM);
    tabbedPane.addTab("Parts", partBusyPanel);
    tabbedPane.addTab("Part Editor", textScrollPane);
    tabbedPane.setEnabledAt(1, false);
    add(tabbedPane, BorderLayout.CENTER);

    tablePopupMenu = new JPopupMenu();

    // We do the part loading in background and display a busy panel while loading

    SwingWorker<ArrayList<Part>, Void> w = new SwingWorker<ArrayList<Part>, Void>() {

        @Override
        protected ArrayList<Part> doInBackground() {
            partBusyPanel.setBusy(true);
            try {
                return AppContext.getContext().getBean(PartFactory.class).getAvailableParts();
            } catch (Exception e) {
                ErrorUtils.showErrorDialog(e);
                return new ArrayList<Part>();
            }
        }

        @Override
        protected void done() {
            log.info("Done loading parts.");
            try {
                model = new PartTableModel(get());
                partPanel.getPartTable().setModel(model);
            } catch (Exception e) {
                ErrorUtils.showErrorDialog(e);
            }
            partBusyPanel.setBusy(false);
            partPanel.transferFocus();
        }
    };

    partPanel.getPartTable().getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            JXTable table = partPanel.getPartTable();
            int[] rows = table.getSelectedRows();
            if (rows.length == 1) {
                if (model == null)
                    return;
                Part selectedPart = model.getParts().get(table.convertRowIndexToModel(rows[0]));
                currentPart = selectedPart;
                selectedRow = table.convertRowIndexToModel(rows[0]);
                partPanel.getImageLabel().setIcon(new ImageIcon(selectedPart.getImage()));
                partPanel.getImageLabel().setText(null);
                partPanel.getPartNameField().setText(selectedPart.getName());
                partPanel.getDescriptionPane().setText(selectedPart.getDescription());
                partPanel.getPackageTypeField().setText(selectedPart.getPackageType());
                partPanel.getAuthorField().setText(selectedPart.getAuthor());
                partPanel.getLicenseField().setText(selectedPart.getLicense());
                tabbedPane.setEnabledAt(1, true);
                textArea.setText(selectedPart.getXmlContent());
            } else {
                currentPart = null;
                partPanel.getImageLabel().setText(resources.getResourceByKey("PartDialog.selectmsg"));
                partPanel.getImageLabel().setIcon(null);
                tabbedPane.setEnabledAt(1, false);
                textArea.setText("");
            }
        }
    });

    partPanel.getPartTable().addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            handlePopupTrigger(e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            handlePopupTrigger(e);
        }
    });

    tablePopupMenu.add(AppContext.getContext().getBean(DeletePartCommand.class));

    // this is the filter configuration for the filter text box on the top
    PartFilter filter = new PartFilter(partPanel.getPartTable());
    BindingGroup filterGroup = new BindingGroup();
    // bind filter JTextBox's text attribute to part tables filterString
    // attribute
    filterGroup.addBinding(Bindings.createAutoBinding(READ, partPanel.getFilterPanel().getFilterTextField(),
            BeanProperty.create("text"), filter, BeanProperty.create("filterString")));
    filterGroup.bind();
    w.execute();

}

From source file:org.pmedv.blackboard.dialogs.DatasheetDialog.java

@Override
protected void initializeComponents() {

    sheetProvider = AppContext.getContext().getBean(DataSheetProvider.class);

    sheetPanel = new DatasheetPanel();
    busyPanel = new JBusyComponent<DatasheetPanel>(sheetPanel);

    setSize(new Dimension(900, 650));
    getContentPanel().add(busyPanel);/*w  w  w . j  a va  2s .  com*/

    SwingWorker<ArrayList<DatasheetBean>, Void> w = new SwingWorker<ArrayList<DatasheetBean>, Void>() {

        @Override
        protected ArrayList<DatasheetBean> doInBackground() throws Exception {
            busyPanel.setBusy(true);
            sheetProvider.loadSheets();
            return sheetProvider.getDatasheetList().getDatasheets();
        }

        @Override
        protected void done() {
            log.info("Done loading sheets.");
            try {
                model = new DataSheetTableModel(get());
                sheetPanel.getDatasheetTable().setModel(model);
            } catch (Exception e) {
                e.printStackTrace();
            }
            busyPanel.setBusy(false);
            sheetPanel.transferFocus();
        }
    };

    getOkButton().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setVisible(false);
        }
    });
    getCancelButton().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            result = OPTION_CANCEL;
            setVisible(false);
        }
    });

    sheetPanel.getDatasheetTable().addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {

                int modelIndex = sheetPanel.getDatasheetTable()
                        .convertRowIndexToModel(sheetPanel.getDatasheetTable().getSelectedRow());
                DatasheetBean sheet = model.getDatasheetBeans().get(modelIndex);

                if (Desktop.isDesktopSupported()) {
                    Desktop desktop = Desktop.getDesktop();
                    try {
                        desktop.open(new File(sheet.getLocation()));
                    } catch (Exception e1) {
                        ErrorUtils.showErrorDialog(e1);
                    }
                }
            }
        }
    });

    sheetPanel.getAddSheetButton().setAction(AppContext.getContext().getBean(AddDatasheetCommand.class));
    sheetPanel.getRemoveSheetButton().setAction(AppContext.getContext().getBean(RemoveDatasheetCommand.class));
    sheetPanel.getImportFolderButton()
            .setAction(AppContext.getContext().getBean(ImportDatasheetFolderCommand.class));

    // create filter for sheets
    DataSheetFilter filter = new DataSheetFilter(sheetPanel.getDatasheetTable());
    BindingGroup filterGroup = new BindingGroup();

    // bind filter JTextBox's text attribute to part tables filterString attribute
    filterGroup.addBinding(Bindings.createAutoBinding(READ, sheetPanel.getFilterPanel().getFilterTextField(),
            BeanProperty.create("text"), filter, BeanProperty.create("filterString")));
    filterGroup.bind();
    w.execute();

}

From source file:org.pmedv.blackboard.dialogs.PartDialog.java

@Override
protected void initializeComponents() {

    partPanel = new PartPanel();
    partBusyPanel = new JBusyComponent<PartPanel>(partPanel);

    setSize(new Dimension(900, 750));

    textArea = new RSyntaxTextArea();
    textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_XML);
    RTextScrollPane textScrollPane = new RTextScrollPane(textArea);

    CompletionProvider provider = createCompletionProvider();
    AutoCompletion ac = new AutoCompletion(provider);
    ac.install(textArea);//w  w w . j a va2 s  . c  om

    JPopupMenu popup = textArea.getPopupMenu();
    popup.addSeparator();
    popup.add(new JMenuItem(new SaveAction()));

    tabbedPane = new JTabbedPane(JTabbedPane.BOTTOM);
    tabbedPane.addTab("Parts", partBusyPanel);
    tabbedPane.addTab("Part Editor", textScrollPane);
    tabbedPane.setEnabledAt(1, false);
    getContentPanel().add(tabbedPane);

    tablePopupMenu = new JPopupMenu();

    // We do the part loading in background and display a busy panel while loading

    SwingWorker<ArrayList<Part>, Void> w = new SwingWorker<ArrayList<Part>, Void>() {

        @Override
        protected ArrayList<Part> doInBackground() {
            partBusyPanel.setBusy(true);
            try {
                return AppContext.getContext().getBean(PartFactory.class).getAvailableParts();
            } catch (Exception e) {
                ErrorUtils.showErrorDialog(e);
                return new ArrayList<Part>();
            }
        }

        @Override
        protected void done() {
            log.info("Done loading parts.");
            try {
                model = new PartTableModel(get());
                partPanel.getPartTable().setModel(model);
            } catch (Exception e) {
                ErrorUtils.showErrorDialog(e);
            }
            partBusyPanel.setBusy(false);
            partPanel.transferFocus();
        }
    };

    getOkButton().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JXTable table = partPanel.getPartTable();
            result = OPTION_OK;
            selectedParts = new ArrayList<Part>();
            int rows[] = partPanel.getPartTable().getSelectedRows();
            try {
                for (int i = 0; i < rows.length; i++) {
                    selectedParts.add(AppContext.getContext().getBean(PartFactory.class).createPart(
                            model.getParts().get(table.convertRowIndexToModel(rows[i])).getFilename()));
                }
            } catch (Exception e1) {
                ErrorUtils.showErrorDialog(e1);
            }
            setVisible(false);
        }
    });

    getCancelButton().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            result = OPTION_CANCEL;
            setVisible(false);
        }
    });

    getNewButton().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            AppContext.getContext().getBean(CreatePartCommand.class).execute(e);
        }
    });

    partPanel.getPartTable().getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            JXTable table = partPanel.getPartTable();
            int[] rows = table.getSelectedRows();
            if (rows.length == 1) {
                if (model == null)
                    return;
                Part selectedPart = model.getParts().get(table.convertRowIndexToModel(rows[0]));
                currentPart = selectedPart;
                selectedRow = table.convertRowIndexToModel(rows[0]);
                partPanel.getImageLabel().setIcon(new ImageIcon(selectedPart.getImage()));
                partPanel.getImageLabel().setText(null);
                partPanel.getPartNameField().setText(selectedPart.getName());
                partPanel.getDescriptionPane().setText(selectedPart.getDescription());
                partPanel.getPackageTypeField().setText(selectedPart.getPackageType());
                partPanel.getAuthorField().setText(selectedPart.getAuthor());
                partPanel.getLicenseField().setText(selectedPart.getLicense());
                tabbedPane.setEnabledAt(1, true);
                textArea.setText(selectedPart.getXmlContent());
            } else {
                currentPart = null;
                partPanel.getImageLabel().setText(resources.getResourceByKey("PartDialog.selectmsg"));
                partPanel.getImageLabel().setIcon(null);
                tabbedPane.setEnabledAt(1, false);
                textArea.setText("");
            }
        }
    });

    tabbedPane.addChangeListener(new ChangeListener() {
        // This method is called whenever the selected tab changes
        public void stateChanged(ChangeEvent evt) {
            JTabbedPane pane = (JTabbedPane) evt.getSource();
            int index = pane.getSelectedIndex();
            if (index == 0) {
                getTitleLabel().setText(title);
                getSubTitleLabel().setText(subTitle);
            } else {
                getTitleLabel().setText(editTitle);
                getSubTitleLabel().setText(editSubTitle + " : " + currentPart.getName());
            }
        }
    });

    partPanel.getPartTable().addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            handlePopupTrigger(e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            handlePopupTrigger(e);
        }
    });

    tablePopupMenu.add(ctx.getBean(DeletePartCommand.class));

    // this is the filter configuration for the filter text box on the top
    PartFilter filter = new PartFilter(partPanel.getPartTable());
    BindingGroup filterGroup = new BindingGroup();
    // bind filter JTextBox's text attribute to part tables filterString
    // attribute
    filterGroup.addBinding(Bindings.createAutoBinding(READ, partPanel.getFilterPanel().getFilterTextField(),
            BeanProperty.create("text"), filter, BeanProperty.create("filterString")));
    filterGroup.bind();
    w.execute();

}

From source file:org.sleuthkit.autopsy.corecomponents.ThumbnailViewNode.java

@Override
@NbBundle.Messages({ "# {0} - file name",
        "ThumbnailViewNode.progressHandle.text=Generating thumbnail for {0}" })
public Image getIcon(int type) {
    Image icon = null;/*w  w  w. j  ava2s .c  o  m*/

    if (iconCache != null) {
        icon = iconCache.get();
    }

    if (icon != null) {
        return icon;
    } else {
        final Content content = this.getLookup().lookup(Content.class);
        if (content == null) {
            return ImageUtils.getDefaultThumbnail();
        }
        if (swingWorker == null || swingWorker.isDone()) {
            swingWorker = new SwingWorker<Image, Object>() {
                final private ProgressHandle progressHandle = ProgressHandle
                        .createHandle(Bundle.ThumbnailViewNode_progressHandle_text(content.getName()));

                @Override
                protected Image doInBackground() throws Exception {
                    progressHandle.start();
                    return ImageUtils.getThumbnail(content, iconSize);
                }

                @Override
                protected void done() {
                    super.done();
                    try {
                        iconCache = new SoftReference<>(super.get());
                        fireIconChange();
                    } catch (InterruptedException | ExecutionException ex) {
                        Logger.getLogger(ThumbnailViewNode.class.getName()).log(Level.SEVERE,
                                "Error getting thumbnail icon for " + content.getName(), ex); //NON-NLS
                    } finally {
                        progressHandle.finish();
                        if (timer != null) {
                            timer.stop();
                            timer = null;

                        }
                        swingWorker = null;
                    }
                }
            };
            swingWorker.execute();
        }
        if (timer == null) {
            timer = new Timer(100, (ActionEvent e) -> {
                fireIconChange();
            });
            timer.start();
        }
        return waitingIcon;
    }
}

From source file:org.sonar.ide.ui.ModulePanel.java

private void reload() {
    reloadButton.setText("Loading...");
    reloadButton.setEnabled(false);/*from w w  w  .  j av a  2  s .  c  om*/
    groupId.setEnabled(false);
    artifactId.setEnabled(false);
    branch.setEnabled(false);

    new SwingWorker<Void, Void>() {

        @Override
        protected Void doInBackground() throws Exception {
            metadataClient.load();
            return null;
        }

        @Override
        protected void done() {
            reloadButton.setText("Reload");
            reloadButton.setEnabled(true);
            groupId.setEnabled(true);
            artifactId.setEnabled(true);
            branch.setEnabled(true);

            refreshGroups();
            setGroupId(currentGroupId);

            refreshArtifacts();
            setArtifactId(currentArtifactId);

            refreshBranches();
            setBranch(currentBranch);
        }
    }.execute();
}

From source file:org.ut.biolab.medsavant.client.project.ProjectWizard.java

private AbstractWizardPage getCompletionPage() {
    final ProgressWheel pw = new ProgressWheel();
    final JPanel p = new JPanel();
    p.setOpaque(false);/*from  ww  w.  j a  v a  2 s.  c o m*/
    p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
    final CompletionWizardPage page = new CompletionWizardPage(PAGENAME_COMPLETE) {
        @Override
        public void setupWizardButtons() {
            fireButtonEvent(ButtonEvent.HIDE_BUTTON, ButtonNames.BACK);
            fireButtonEvent(ButtonEvent.HIDE_BUTTON, ButtonNames.NEXT);
            if (modify) {
                fireButtonEvent(ButtonEvent.ENABLE_BUTTON, ButtonNames.FINISH);
            } else {
                fireButtonEvent(ButtonEvent.HIDE_BUTTON, ButtonNames.FINISH);

                new SwingWorker() {
                    @Override
                    protected Object doInBackground() throws Exception {
                        try {
                            createNewProject();
                        } catch (Exception e) {
                            DialogUtils.displayException("Error", "Error trying to create project", e);
                            LOG.error(e);
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void done() {
                        pw.setComplete();
                        p.setVisible(true);
                        fireButtonEvent(ButtonEvent.ENABLE_BUTTON, ButtonNames.FINISH);
                        revalidate();
                        repaint();
                    }
                }.execute();
            }
        }
    };

    if (modify) {
        page.addText("You have completed the project modification process.");
    } else {
        page.addText("Creating project...");
        page.addComponent(pw);
        p.add(new JLabel("Complete."));
        p.add(Box.createHorizontalGlue());
        page.addComponent(p);
        p.setVisible(false);

        /*p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
         p.add(pw, Box.createHorizontalGlue());
         p.add(pw, BorderLayout.CENTER);
         p.add(pw, Box.createHorizontalGlue());
         page.addComponent(p);*/
    }

    return page;
}