Example usage for javax.swing SwingWorker execute

List of usage examples for javax.swing SwingWorker execute

Introduction

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

Prototype

public final void execute() 

Source Link

Document

Schedules this SwingWorker for execution on a worker thread.

Usage

From source file:pl.exsio.ck.logging.presenter.LogPresenterImpl.java

@Override
public void log(final String msg) {
    SwingWorker worker = new SwingWorker() {

        @Override/*from  w  w  w  .j  a v a  2 s  .  c o  m*/
        protected Object doInBackground() throws Exception {

            view.getLogArea().append(sdf.format(new Date()) + ": " + msg + "\n");
            return null;
        }

    };
    worker.execute();
}

From source file:pl.exsio.ck.logging.presenter.LogPresenterImpl.java

@Override
public void clean() {
    SwingWorker worker = new SwingWorker() {

        @Override/*from   w w w  .j ava  2s .c  o  m*/
        protected Object doInBackground() throws Exception {
            view.getLogArea().setText("");
            return null;
        }

    };
    worker.execute();
}

From source file:pt.lsts.neptus.console.plugins.ImageLayers.java

private Future<ImageLayer> addLayer(final File f) {
    final SwingWorker<ImageLayer, Object> worker = new SwingWorker<ImageLayer, Object>() {
        @Override/*from w ww.  ja va2 s.  com*/
        protected ImageLayer doInBackground() throws Exception {
            note = "loading layer in " + f.getAbsolutePath();
            ImageLayer il = ImageLayer.read(f);
            layers.add(il);
            files.add(f);
            note = "";
            layerFiles = StringUtils.join(files, ",");
            rebuildControls();
            return il;
        }
    };
    worker.execute();
    return worker;
}

From source file:pt.lsts.neptus.mra.MRAFilesHandler.java

/**
 * Generates PDF report from log file.//from w w w.  j  ava  2s.  c  o  m
 */
public void generatePDFReport(final File f) {

    SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>() {
        @Override
        protected Boolean doInBackground() throws Exception {
            //                GuiUtils.infoMessage(mra, I18n.text("Generating PDF Report..."), I18n.text("Generating PDF Report..."));
            mra.getMRAMenuBar().getReportMenuItem().setEnabled(false);
            LsfReportProperties.generatingReport = true;
            mra.getMraPanel().addStatusBarMsg("Generating Report...");
            return LsfReport.generateReport(mra.getMraPanel().getSource(), f, mra.getMraPanel());
        }

        @Override
        protected void done() {
            super.done();
            try {
                get();
            } catch (Exception e) {
                NeptusLog.pub().error(e);
            }
            try {
                if (get()) {
                    GuiUtils.infoMessage(mra, I18n.text("Generate PDF Report"),
                            I18n.text("File saved to") + " " + f.getAbsolutePath());
                    final String pdfF = f.getAbsolutePath();
                    int resp = GuiUtils.confirmDialog(mra, I18n.text("Open PDF Report"),
                            I18n.text("Do you want to open PDF Report file?"));
                    if (resp == JOptionPane.YES_OPTION) {
                        new Thread() {
                            @Override
                            public void run() {
                                openPDFInExternalViewer(pdfF);
                            };
                        }.start();
                    }
                }
            } catch (Exception e) {
                GuiUtils.errorMessage(mra, I18n.text("PDF Creation Process"),
                        "<html>" + I18n.text("PDF <b>was not</b> saved to file.") + "<br>" + I18n.text("Error")
                                + ": " + e.getMessage() + "</html>");
                e.printStackTrace();
            } finally {
                mra.getBgp().block(false);
                mra.getMRAMenuBar().getReportMenuItem().setEnabled(true);
                LsfReportProperties.generatingReport = false;
                mra.getMraPanel().reDrawStatusBar();
            }
        }
    };
    worker.execute();
}

From source file:richtercloud.document.scanner.components.OCRResultPanel.java

private void startOCR() {
    String oCRResult = null;/*from  w ww  .  j  a v a  2  s. co m*/
    if (!cancelable) {
        oCRResult = this.oCRResultPanelFetcher.fetch();
    } else {
        showProgressMonitor();
        final SwingWorker<String, String> oCRThread = new SwingWorker<String, String>() {
            private final OCRResultPanelFetcherProgressListener progressListener = new OCRResultPanelFetcherProgressListener() {
                @Override
                public void onProgressUpdate(OCRResultPanelFetcherProgressEvent progressEvent) {
                    int progress = (int) (progressEvent.getProgress() * 100);
                    if (progressMonitor != null) {
                        //might be null if the panel isn't displayed yet
                        progressMonitor.setProgress(progress);
                    }
                }
            };

            @Override
            public String doInBackground() {
                oCRResultPanelFetcher.addProgressListener(progressListener);
                try {
                    Thread thread1 = new Thread() {
                        @Override
                        public void run() {
                            while (!isDone()) {
                                if (progressMonitor != null && progressMonitor.isCanceled()) {
                                    oCRResultPanelFetcher.cancelFetch();
                                    break;
                                }
                                try {
                                    Thread.sleep(100);
                                } catch (InterruptedException ex) {
                                    throw new RuntimeException(ex);
                                }
                            }
                        }
                    };
                    thread1.start();
                    String retValue = oCRResultPanelFetcher.fetch();
                    return retValue;
                } catch (Exception ex) {
                    progressMonitor.setProgress(101);
                    messageHandler.handle(new Message(
                            String.format("An exception during fetching OCR result occured: %s",
                                    ExceptionUtils.getRootCauseMessage(ex)),
                            JOptionPane.ERROR_MESSAGE, "Exception occured"));
                }
                return null;
            }

            @Override
            protected void done() {
                oCRResultPanelFetcher.removeProgressListener(progressListener);
                progressMonitor.setProgress(101);
            }
        };
        oCRThread.execute();
        try {
            oCRResult = oCRThread.get();
        } catch (InterruptedException | ExecutionException ex) {
            throw new RuntimeException(ex);
        }
    }
    if (oCRResult != null) {
        //might be null if fetch has been canceled (this check is
        //unnecessary for non-cancelable processing, but don't care
        this.oCRResultTextArea.setText(oCRResult);
    }
}

From source file:richtercloud.document.scanner.gui.MainPanel.java

/**
 * Uses a modal dialog in order to display the progress of the retrieval and
 * make the operation cancelable.//from ww w  .  ja va2  s.co  m
 * @param documentFile
 * @return the retrieved images or {@code null} if the retrieval has been
 * canceled (in dialog)
 * @throws DocumentAddException
 * @throws InterruptedException
 * @throws ExecutionException
 */
/*
internal implementation notes:
- can't use ProgressMonitor without blocking EVT instead of a model dialog
when using SwingWorker.get
*/
public List<BufferedImage> retrieveImages(final File documentFile)
        throws DocumentAddException, InterruptedException, ExecutionException {
    if (documentFile == null) {
        throw new IllegalArgumentException("documentFile mustn't be null");
    }
    final SwingWorkerGetWaitDialog dialog = new SwingWorkerGetWaitDialog(SwingUtilities.getWindowAncestor(this), //owner
            DocumentScanner.generateApplicationWindowTitle("Wait", APP_NAME, APP_VERSION), //dialogTitle
            "Retrieving image data", //labelText
            null //progressBarText
    );
    final SwingWorker<List<BufferedImage>, Void> worker = new SwingWorker<List<BufferedImage>, Void>() {
        @Override
        protected List<BufferedImage> doInBackground() throws Exception {
            List<BufferedImage> retValue = new LinkedList<>();
            try {
                InputStream pdfInputStream = new FileInputStream(documentFile);
                PDDocument document = PDDocument.load(pdfInputStream);
                @SuppressWarnings("unchecked")
                List<PDPage> pages = document.getDocumentCatalog().getAllPages();
                for (PDPage page : pages) {
                    if (dialog.isCanceled()) {
                        document.close();
                        MainPanel.LOGGER.debug("tab generation aborted");
                        return null;
                    }
                    BufferedImage image = page.convertToImage();
                    retValue.add(image);
                }
                document.close();
            } catch (IOException ex) {
                throw new DocumentAddException(ex);
            }
            return retValue;
        }

        @Override
        protected void done() {
        }
    };
    worker.addPropertyChangeListener(new SwingWorkerCompletionWaiter(dialog));
    worker.execute();
    //the dialog will be visible until the SwingWorker is done
    dialog.setVisible(true);
    List<BufferedImage> retValue = worker.get();
    return retValue;
}

From source file:richtercloud.document.scanner.gui.MainPanel.java

/**
 *
 * @param images images to be transformed into a {@link OCRSelectPanelPanel}
 * or {@code null} indicating that no scan data was persisted when opening a
 * persisted entry/* ww w .j  av  a2  s .com*/
 * @param documentFile The {@link File} the document is stored in.
 * {@code null} indicates that the document has not been saved yet (e.g. if
 * the {@link OCRSelectComponent} represents scan data).
 * @throws DocumentAddException
 */
public void addDocument(final List<BufferedImage> images, final File documentFile, final Object entityToEdit)
        throws DocumentAddException {
    if (ADD_DOCUMENT_ASYNC) {
        final ProgressMonitor progressMonitor = new ProgressMonitor(this, //parent
                "Generating new document tab", //message
                null, //note
                0, //min
                100 //max
        );
        progressMonitor.setMillisToPopup(0);
        progressMonitor.setMillisToDecideToPopup(0);
        final SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
            private OCRSelectComponent createdOCRSelectComponentScrollPane;

            @Override
            protected Void doInBackground() throws Exception {
                try {
                    this.createdOCRSelectComponentScrollPane = addDocumentRoutine(images, documentFile,
                            entityToEdit, progressMonitor);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                return null;
            }

            @Override
            protected void done() {
                progressMonitor.close();
                addDocumentDone(this.createdOCRSelectComponentScrollPane);
            }
        };
        worker.execute();
        progressMonitor.setProgress(1); //ProgressMonitor dialog blocks until SwingWorker.done
        //is invoked
    } else {
        OCRSelectComponent oCRSelectComponentScrollPane = addDocumentRoutine(images, documentFile, entityToEdit,
                null //progressMonitor
        );
        addDocumentDone(oCRSelectComponentScrollPane);
    }
}

From source file:RosAdProgram.model.Model.java

public void copy() {
    final File open = getOpenPath();
    final File save = getSavePath();
    final double probability = getProbability();
    resetErrors();/*  w  w w .  j  a v a  2  s  .  co  m*/

    SwingWorker<Void, Integer[]> worker = new SwingWorker<Void, Integer[]>() { //  ? progressBar
        @Override
        protected Void doInBackground() throws Exception {
            FileInputStream in = null;
            FileOutputStream out = null;

            try {
                try {
                    in = new FileInputStream(open);
                } catch (FileNotFoundException ex) {
                    System.out.println("   ");
                    Logger.getLogger(ConfigGUI.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    out = new FileOutputStream(save);
                } catch (FileNotFoundException ex) {
                    System.out.println("?   ");
                    Logger.getLogger(ConfigGUI.class.getName()).log(Level.SEVERE, null, ex);
                }
                int c;

                try { // Noise adding 
                    Integer[] data = new Integer[6];
                    data[0] = 0; // ? ? 
                    data[1] = 0; // ?  
                    data[2] = 0; // ?  
                    data[3] = 0; // ?  
                    data[4] = 0; // ? ? 
                    data[5] = 0; // ? ? 

                    int currentBlockCount = 0; //  ? ? 
                    int blockSize = getBlockSize(); //    
                    int bytes = 0; // ? ? 

                    for (int bytesInBlockCounter = 0; (c = in.read()) != -1;) { // ? . (? ?  - ?  )
                        bytes++; // ? ? 
                        bytesInBlockCounter++;
                        int result = mask(probability, c); // result - 8   ? ? 
                        out.write(result); // ?  ?                         
                        if ((bytesInBlockCounter == blockSize) || (getFileSize() == bytes - 1)) { //      ?  
                            //      ?  (   ?  ,
                            //  ?    )
                            if (getByteErrorFlag()) {
                                setBlockError(1);
                                setBlockErrorFlag(false); //     
                            }
                            currentBlockCount++; //  ? 
                            bytesInBlockCounter = 0; // ?? ?   
                        }
                        data[0] = getPercent(bytes + 1);
                        data[1] = getBitError();
                        data[2] = getByteError();
                        data[3] = getBlockError();
                        data[4] = bytes;
                        data[5] = currentBlockCount;

                        publish(data);
                    }
                    System.out.println("? :");
                    System.out.println(" " + getBitError());
                    System.out.println(" " + getByteError());
                    System.out.println(" " + getBlockError());

                } catch (IOException ex) {
                    System.out.println("   ?");
                    Logger.getLogger(ConfigGUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException ex) {
                        Logger.getLogger(ConfigGUI.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException ex) {
                        Logger.getLogger(ConfigGUI.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
            return null;
        }

        @Override
        // This will be called if you call publish() from doInBackground()
        // Can safely update the GUI here.
        protected void process(List<Integer[]> chunks) { // ?    
                                                         // publish ?
            Integer[] value = chunks.get(chunks.size() - 1); // ?
            statisticsGUI.setProgress(value[0]); //  ??
            statisticsGUI.setValueButtomTable(value[1], value[2], value[3], value[4], value[5]); //  ?    ??

        }
    };
    worker.execute();
}

From source file:ru.goodfil.catalog.ui.forms.CarsPanel.java

private void filterSearchBtnActionPerformed(ActionEvent e) {
    final String filterCode = filterSearchField.getText();
    if (StringUtils.isBlank(filterCode)) {
        String msg = "? ?    \"\"";
        JOptionPane.showMessageDialog(null, msg, "!", JOptionPane.WARNING_MESSAGE);
        return;/*w w w  .j  a v a 2  s.c  om*/
    }

    SwingWorker worker = new SwingWorker<Object, Void>() {
        @Override
        protected Object doInBackground() throws Exception {
            allFilters.clear();
            allFilters.addAll(filtersService.getFiltersByName(filterCode));
            return null;
        }
    };
    worker.execute();

    adjustButtonsEnabledProperty();
}

From source file:screenieup.ImgurUpload.java

/**
 * Upload image.//from  w  ww .  ja v a 2s. com
 * @param imgToUpload the image to upload
 */
public void upload(BufferedImage imgToUpload) {
    System.out.println("Preparing for upload...");
    final BufferedImage img = imgToUpload; // was turned into 'final' when using JDK 7 to compile
    SwingWorker uploader;
    uploader = new SwingWorker<Void, Integer>() {
        @Override
        protected Void doInBackground() {
            publish(0);
            ByteArrayOutputStream baos = writeImage(img);
            publish(1);
            String dataToSend = encodeImage(baos);
            publish(2);
            URLConnection connection = connect();
            publish(3);
            sendImage(connection, dataToSend);
            publish(4);
            String response = getResponse(connection);
            publish(5);
            getImageLinks(response);
            return null;
        }

        @Override
        protected void done() {
            publish(6);
            copyToClipBoard();
            publish(7);
            urlarea.setText(imgurl);
            urlarea.setEnabled(true);
            browserBtn.setEnabled(true);
            new ListWriter("imgur_links.txt").writeList(
                    "Image link: " + imgurl + " - Image delete link: " + IMGUR_DELETE_URI + imgurl_del, true); // true = append to file, false = overwrite
            JOptionPane.showMessageDialog(null, "Uploaded!\n"
                    + "The image link has been copied to your clipboard!\nImage link and deletion link has been logged to file.");
            progressDialog.dispose();
        }

        @Override
        protected void process(List<Integer> chunks) {
            progressLabel.setText(progressText[chunks.get(chunks.size() - 1)]); // The last value in this array is all we care about.
            progressBar.setValue(chunks.get(chunks.size() - 1) + 1);
        }
    };
    uploader.execute();
}