Example usage for javax.swing ProgressMonitor ProgressMonitor

List of usage examples for javax.swing ProgressMonitor ProgressMonitor

Introduction

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

Prototype

public ProgressMonitor(Component parentComponent, Object message, String note, int min, int max) 

Source Link

Document

Constructs a graphic object that shows progress, typically by filling in a rectangular bar as the process nears completion.

Usage

From source file:jamel.gui.JamelWindow.java

/**
 * Exports a rapport./*www.ja  v  a2 s. co  m*/
 */
public void exportRapport() {
    final int max = tabbedPane.getTabCount();
    final ProgressMonitor progressMonitor = new ProgressMonitor(this, "Exporting", "", 0, max);
    progressMonitor.setMillisToDecideToPopup(0);
    final String rc = System.getProperty("line.separator");
    final File outputDirectory = new File("exports/" + this.getTitle() + "-" + (new Date()).getTime());
    outputDirectory.mkdir();
    try {
        final FileWriter writer = new FileWriter(new File(outputDirectory, "Rapport.html"));
        writer.write("<HTML>" + rc);
        writer.write("<HEAD>");
        writer.write("<TITLE>" + this.getTitle() + "</TITLE>" + rc);
        writer.write("</HEAD>" + rc);
        writer.write("<BODY>" + rc);
        writer.write("<H1>" + this.getTitle() + "</H1>" + rc);
        writer.write("<HR>" + rc);
        final Date start = viewManager.getStart().getDate();
        final Date end = viewManager.getEnd().getDate();
        for (int tabIndex = 0; tabIndex < max; tabIndex++) {
            try {
                final JPanel currentTab = (JPanel) tabbedPane.getComponentAt(tabIndex);
                final String tabTitle = tabbedPane.getTitleAt(tabIndex);
                writer.write("<H2>" + tabTitle + "</H2>" + rc);
                writer.write("<TABLE>" + rc);
                final int chartPanelCount = currentTab.getComponentCount();
                for (int chartIndex = 0; chartIndex < chartPanelCount; chartIndex++) {
                    if ((chartIndex == 3) | (chartIndex == 6))
                        writer.write("<TR>" + rc);
                    final ChartPanel aChartPanel = (ChartPanel) currentTab.getComponent(chartIndex);
                    final JamelChart chart = (JamelChart) aChartPanel.getChart();
                    if (chart != null) {
                        final String chartTitle = chart.getTitle().getText();
                        if (!chartTitle.equals("Empty")) {
                            try {
                                chart.setTitle("");
                                chart.setTimeRange(start, end);
                                String imageName = (tabTitle + "-" + chartIndex + "-" + chartTitle + ".png")
                                        .replace(" ", "_").replace("&", "and");
                                ChartUtilities.saveChartAsPNG(new File(outputDirectory, imageName), chart,
                                        aChartPanel.getWidth(), aChartPanel.getHeight());
                                writer.write("<TD><IMG src=\"" + imageName + "\" title=\"" + chartTitle + "\">"
                                        + rc);
                                chart.setTitle(chartTitle);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                writer.write("</TABLE>" + rc);
                writer.write("<HR>" + rc);
            } catch (ClassCastException e) {
            }
            progressMonitor.setProgress(tabIndex);
        }
        writer.write("<H2>Scenario</H2>" + rc);
        writer.write(this.consoleText.toString());
        writer.write("</BODY>" + rc);
        writer.write("</HTML>" + rc);
        writer.close();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    progressMonitor.close();
}

From source file:org.usfirst.frc.team2084.neuralnetwork.HeadingNeuralNetworkTrainer.java

private void trainNetwork() {
    if (!training) {

        // Set training flag and disable button
        training = true;/*from   w w w  .j  a v a2  s.c  o  m*/
        trainButton.setEnabled(false);

        final ProgressMonitor progressMonitor = new ProgressMonitor(frame, "Training Network...", "", 0, 100);
        progressMonitor.setMillisToDecideToPopup(100);
        progressMonitor.setMillisToPopup(400);

        @SuppressWarnings("unchecked")
        final ArrayList<XYDataItem> data = new ArrayList<>(outputGraphDataSeries.getItems());

        final int maxProgress = iterations * data.size();

        final SwingWorker<Void, Void> trainingWorker = new SwingWorker<Void, Void>() {

            @Override
            protected Void doInBackground() throws Exception {
                // Reset the neural network to default values
                synchronized (this) {
                    network.reset();
                    network.setEta(eta);
                    network.setMomentum(momentum);
                }

                outer: for (int j = 0; j < iterations; j++) {
                    for (int i = 0; i < data.size(); i++) {
                        if (!isCancelled()) {
                            XYDataItem d = data.get(i);
                            double error = convertAngleToInput(d.getXValue());
                            double output = d.getYValue();
                            synchronized (this) {
                                network.feedForward(error);
                                network.backPropagation(output);
                            }
                            int jl = j;
                            int il = i;
                            int progress = (int) (((float) (data.size() * jl + il + 1) / maxProgress) * 100);
                            setProgress(progress);
                        } else {
                            break outer;
                        }
                    }
                }

                displayNetwork();
                return null;
            }

            @Override
            protected void done() {
                training = false;
                trainButton.setEnabled(true);
                progressMonitor.close();
            }
        };
        trainingWorker.addPropertyChangeListener(new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("progress")) {
                    progressMonitor.setProgress((int) evt.getNewValue());
                }
                if (progressMonitor.isCanceled()) {
                    trainingWorker.cancel(true);
                }
            }
        });
        trainingWorker.execute();
    }
}

From source file:hermes.store.schema.DefaultJDBCAdapter.java

private void executeStatements(Connection connection, String[] statements) throws SQLException {
    final StringBuffer message = new StringBuffer();
    ProgressMonitor progressMonitor = null;

    if (HermesBrowser.getBrowser() != null) {
        progressMonitor = new ProgressMonitor(HermesBrowser.getBrowser(), "Initialising message stores... ",
                "Connecting...", 0, statements.length);

        progressMonitor.setMillisToDecideToPopup(100);
        progressMonitor.setMillisToPopup(400);
    }//from www.j  a v  a  2s . c o m

    final QueryRunner runner = new QueryRunner();

    for (int i = 0; i < statements.length; i++) {
        try {
            log.debug("executing: " + statements[i]);

            if (progressMonitor != null) {
                progressMonitor.setProgress(statements.length);
                progressMonitor.setNote("Executing statement " + i + " of " + statements.length);
            }

            runner.update(connection, statements[i]);
        } catch (SQLException ex) {
            log.error(ex.getMessage());
        }
    }
}

From source file:OAT.trading.thread.BacktestThread.java

@Override
public void run() {
    if (symbol == null || keys == null || steps == null || backDate == null) {
        return;/*from  w  w w .  j a  va 2  s .  c o  m*/
    }

    setState(true, State.BACKTESTING);
    threadCount = 0;

    Main.frame.selectLogTextPane(getDefaultLoggerName());

    cleanup();

    logger.setLevel(logLevel);

    startTime = DateUtil.getTimeNow();

    log(Level.INFO, "Starting Backtest {0} for {1}...",
            new Object[] { symbol, backDate.toString().toLowerCase() });

    //Preparing
    if (strategies != null) {
        for (BacktestStrategy strategy : strategies) {
            strategy.removeChangeListener(this);
            strategy = null;
        }

        strategies = null;
    }

    // clear all backtest tables
    if (!appendResults) {
        try {
            getBacktestSchema().truncateTables();
        } catch (Exception ex) {
            log(Level.SEVERE, null, ex);
        }
    }

    strategies = new ArrayList<BacktestStrategy>();

    // get data
    if (getBacktestData() != null && symbol.equals(getBacktestData().symbol) && backDate != BackDate.TODAY
            && backDate == getBacktestData().getBackDate()
            && getBacktestData().getDuration() < DateUtil.DAY_TIME) {
    } else {

        setBacktestData(new BacktestData(symbol));

        try {
            getBacktestData().getTicksData(expiryMonths, lastDay, backDate);

        } catch (UnsupportedOperationException e) {
            log(Level.INFO, "User canceled.");
            setBacktestData(null);
            return;

        } catch (Exception e) {
            log(Level.SEVERE, null, e);
        }

    }

    try {
        getBacktestSchema().insertBacktestDay(getBacktestData());
    } catch (Exception e) {
        log(Level.SEVERE, null, e);
    }

    daysCount = getBacktestData().size();

    String dayCountString = TextUtil.BASIC_FORMATTER.format(daysCount);
    log(Level.INFO, "{0} trading sessions found.", dayCountString);

    int tickCount = 0;
    for (int i = 0; i < getBacktestData().size(); i++) {
        tickCount += getBacktestData().getTickDataset(i).size();

    }

    log(Level.INFO, "Calculating combinations...");

    combinations = GeneralUtil.extractCombinations(steps);

    totalTicks = tickCount * combinations.length;
    totalBacktests = getBacktestData().size() * combinations.length;
    finishedBacktests = 0;

    progressStartTime = DateUtil.getTimeNow();
    progressMonitor = new ProgressMonitor(Main.frame,
            "Running Backtest.                                           ", "", 0, totalBacktests);
    //progressMonitor.setProgress(0);

    //log combinations
    StringBuilder sb = new StringBuilder("Combinations:\n");
    for (int i = 0; i < combinations.length; i++) {
        sb.append("[").append(i).append("]  ").append(TextUtil.toString(combinations[i], ",")).append("\n");
    }
    log(Level.FINE, sb.toString());

    String count = TextUtil.BASIC_FORMATTER.format(combinations.length);

    log(Level.INFO,
            "\n\tTotal Combinations = {0}" + "\n\tTotal number of ticks = {1} x {2} = {3}"
                    + "\n\tTotal number of backtests = {4} x {5} = {6}",
            new Object[] { combinations.length, TextUtil.BASIC_FORMATTER.format(tickCount), count,
                    TextUtil.BASIC_FORMATTER.format(totalTicks), dayCountString, count, totalBacktests });

    new Thread(new Runnable() {

        @Override
        public void run() {
            for (int j = 0; j < combinations.length; j++) {
                for (int i = 0; i < getBacktestData().size(); i++) {
                    if (progressMonitor.isCanceled()) {
                        break;
                    }

                    final BacktestStrategy strategy = new BacktestStrategy();
                    final TickDataset tickDataset = getBacktestData().getTickDataset(i);
                    ContractDetails contractDetails = getBacktestData().getContractDetails(i);
                    TradingHours tradingHours = getBacktestData().getTradingHours(i);

                    try {
                        Parameters[] params = GeneralUtil.getParameters(keys, combinations[j]);
                        strategy.setLogger(logger);
                        strategy.setThreadId(strategies.size());
                        strategy.setDataClient(dataClient);
                        strategy.setTradingClient(tradingClient);
                        strategy.setParameters(params);

                        if (contractDetails == null) {
                            log(Level.WARNING, "Contract not found for dayId: {0}", i);
                        }

                        strategy.initBacktest(i, j,
                                //                                    tickDataset,
                                contractDetails, tradingHours, commission);

                        strategies.add(strategy);

                        if (tickDataset.getNewBarCount() > tradingHours.getSessions().size()) {
                            totalBacktests--;
                            progressMonitor.setMaximum(totalBacktests);

                            continue;
                        }

                        waitForThread(Main.p_Backtest_Max_Thread);

                        strategy.setTicksDataset(tickDataset);
                        new Thread(strategy).start();

                        threadCount++;

                    } catch (Exception ex) {
                        log(Level.SEVERE, null, ex);
                    }
                }
            }

        }
    }).start();
}

From source file:com.marginallyclever.makelangelo.MainGUI.java

protected boolean LoadDXF(String filename) {
    if (ChooseImageConversionOptions(true) == false)
        return false;

    // where to save temp output file?
    final String destinationFile = GetTempDestinationFile();
    final String srcFile = filename;

    TabToLog();/* w  w w. ja v a 2  s  . c  o m*/

    final ProgressMonitor pm = new ProgressMonitor(null, translator.get("Converting"), "", 0, 100);
    pm.setProgress(0);
    pm.setMillisToPopup(0);

    final SwingWorker<Void, Void> s = new SwingWorker<Void, Void>() {
        public boolean ok = false;

        @SuppressWarnings("unchecked")
        @Override
        public Void doInBackground() {
            Log("<font color='green'>" + translator.get("Converting") + " " + destinationFile + "</font>\n");

            Parser parser = ParserBuilder.createDefaultParser();

            double dxf_x2 = 0;
            double dxf_y2 = 0;
            OutputStreamWriter out = null;

            try {
                out = new OutputStreamWriter(new FileOutputStream(destinationFile), "UTF-8");
                DrawingTool tool = machineConfiguration.GetCurrentTool();
                out.write(machineConfiguration.GetConfigLine() + ";\n");
                out.write(machineConfiguration.GetBobbinLine() + ";\n");
                out.write("G00 G90;\n");
                tool.WriteChangeTo(out);
                tool.WriteOff(out);

                parser.parse(srcFile, DXFParser.DEFAULT_ENCODING);
                DXFDocument doc = parser.getDocument();
                Bounds b = doc.getBounds();
                double width = b.getMaximumX() - b.getMinimumX();
                double height = b.getMaximumY() - b.getMinimumY();
                double cx = (b.getMaximumX() + b.getMinimumX()) / 2.0f;
                double cy = (b.getMaximumY() + b.getMinimumY()) / 2.0f;
                double sy = machineConfiguration.GetPaperHeight() * 10 / height;
                double sx = machineConfiguration.GetPaperWidth() * 10 / width;
                double scale = (sx < sy ? sx : sy) * machineConfiguration.paper_margin;
                sx = scale * (machineConfiguration.reverseForGlass ? -1 : 1);
                // count all entities in all layers
                Iterator<DXFLayer> layer_iter = (Iterator<DXFLayer>) doc.getDXFLayerIterator();
                int entity_total = 0;
                int entity_count = 0;
                while (layer_iter.hasNext()) {
                    DXFLayer layer = (DXFLayer) layer_iter.next();
                    Log("<font color='yellow'>Found layer " + layer.getName() + "</font>\n");
                    Iterator<String> entity_iter = (Iterator<String>) layer.getDXFEntityTypeIterator();
                    while (entity_iter.hasNext()) {
                        String entity_type = (String) entity_iter.next();
                        List<DXFEntity> entity_list = (List<DXFEntity>) layer.getDXFEntities(entity_type);
                        Log("<font color='yellow'>+ Found " + entity_list.size() + " of type " + entity_type
                                + "</font>\n");
                        entity_total += entity_list.size();
                    }
                }
                // set the progress meter
                pm.setMinimum(0);
                pm.setMaximum(entity_total);

                // convert each entity
                layer_iter = doc.getDXFLayerIterator();
                while (layer_iter.hasNext()) {
                    DXFLayer layer = (DXFLayer) layer_iter.next();

                    Iterator<String> entity_type_iter = (Iterator<String>) layer.getDXFEntityTypeIterator();
                    while (entity_type_iter.hasNext()) {
                        String entity_type = (String) entity_type_iter.next();
                        List<DXFEntity> entity_list = layer.getDXFEntities(entity_type);

                        if (entity_type.equals(DXFConstants.ENTITY_TYPE_LINE)) {
                            for (int i = 0; i < entity_list.size(); ++i) {
                                pm.setProgress(entity_count++);
                                DXFLine entity = (DXFLine) entity_list.get(i);
                                Point start = entity.getStartPoint();
                                Point end = entity.getEndPoint();

                                double x = (start.getX() - cx) * sx;
                                double y = (start.getY() - cy) * sy;
                                double x2 = (end.getX() - cx) * sx;
                                double y2 = (end.getY() - cy) * sy;

                                // is it worth drawing this line?
                                double dx = x2 - x;
                                double dy = y2 - y;
                                if (dx * dx + dy * dy < tool.GetDiameter() / 2.0) {
                                    continue;
                                }

                                dx = dxf_x2 - x;
                                dy = dxf_y2 - y;

                                if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) {
                                    if (tool.DrawIsOn()) {
                                        tool.WriteOff(out);
                                    }
                                    tool.WriteMoveTo(out, (float) x, (float) y);
                                }
                                if (tool.DrawIsOff()) {
                                    tool.WriteOn(out);
                                }
                                tool.WriteMoveTo(out, (float) x2, (float) y2);
                                dxf_x2 = x2;
                                dxf_y2 = y2;
                            }
                        } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_SPLINE)) {
                            for (int i = 0; i < entity_list.size(); ++i) {
                                pm.setProgress(entity_count++);
                                DXFSpline entity = (DXFSpline) entity_list.get(i);
                                entity.setLineWeight(30);
                                DXFPolyline polyLine = DXFSplineConverter.toDXFPolyline(entity);
                                boolean first = true;
                                for (int j = 0; j < polyLine.getVertexCount(); ++j) {
                                    DXFVertex v = polyLine.getVertex(j);
                                    double x = (v.getX() - cx) * sx;
                                    double y = (v.getY() - cy) * sy;
                                    double dx = dxf_x2 - x;
                                    double dy = dxf_y2 - y;

                                    if (first == true) {
                                        first = false;
                                        if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) {
                                            // line does not start at last tool location, lift and move.
                                            if (tool.DrawIsOn()) {
                                                tool.WriteOff(out);
                                            }
                                            tool.WriteMoveTo(out, (float) x, (float) y);
                                        }
                                        // else line starts right here, do nothing.
                                    } else {
                                        // not the first point, draw.
                                        if (tool.DrawIsOff())
                                            tool.WriteOn(out);
                                        if (j < polyLine.getVertexCount() - 1
                                                && dx * dx + dy * dy < tool.GetDiameter() / 2.0)
                                            continue; // less than 1mm movement?  Skip it. 
                                        tool.WriteMoveTo(out, (float) x, (float) y);
                                    }
                                    dxf_x2 = x;
                                    dxf_y2 = y;
                                }
                            }
                        } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_POLYLINE)) {
                            for (int i = 0; i < entity_list.size(); ++i) {
                                pm.setProgress(entity_count++);
                                DXFPolyline entity = (DXFPolyline) entity_list.get(i);
                                boolean first = true;
                                for (int j = 0; j < entity.getVertexCount(); ++j) {
                                    DXFVertex v = entity.getVertex(j);
                                    double x = (v.getX() - cx) * sx;
                                    double y = (v.getY() - cy) * sy;
                                    double dx = dxf_x2 - x;
                                    double dy = dxf_y2 - y;

                                    if (first == true) {
                                        first = false;
                                        if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) {
                                            // line does not start at last tool location, lift and move.
                                            if (tool.DrawIsOn()) {
                                                tool.WriteOff(out);
                                            }
                                            tool.WriteMoveTo(out, (float) x, (float) y);
                                        }
                                        // else line starts right here, do nothing.
                                    } else {
                                        // not the first point, draw.
                                        if (tool.DrawIsOff())
                                            tool.WriteOn(out);
                                        if (j < entity.getVertexCount() - 1
                                                && dx * dx + dy * dy < tool.GetDiameter() / 2.0)
                                            continue; // less than 1mm movement?  Skip it. 
                                        tool.WriteMoveTo(out, (float) x, (float) y);
                                    }
                                    dxf_x2 = x;
                                    dxf_y2 = y;
                                }
                            }
                        }
                    }
                }

                // entities finished.  Close up file.
                tool.WriteOff(out);
                tool.WriteMoveTo(out, 0, 0);

                ok = true;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    if (out != null)
                        out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            pm.setProgress(100);
            return null;
        }

        @Override
        public void done() {
            pm.close();
            Log("<font color='green'>" + translator.get("Finished") + "</font>\n");
            PlayConversionFinishedSound();
            if (ok) {
                LoadGCode(destinationFile);
                TabToDraw();
            }
            Halt();
        }
    };

    s.addPropertyChangeListener(new PropertyChangeListener() {
        // Invoked when task's progress property changes.
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == evt.getPropertyName()) {
                int progress = (Integer) evt.getNewValue();
                pm.setProgress(progress);
                String message = String.format("%d%%\n", progress);
                pm.setNote(message);
                if (s.isDone()) {
                    Log("<font color='green'>" + translator.get("Finished") + "</font>\n");
                } else if (s.isCancelled() || pm.isCanceled()) {
                    if (pm.isCanceled()) {
                        s.cancel(true);
                    }
                    Log("<font color='green'>" + translator.get("Cancelled") + "</font>\n");
                }
            }
        }
    });

    s.execute();

    return true;
}

From source file:com.marginallyclever.makelangelo.MainGUI.java

public boolean LoadImage(String filename) {
    // where to save temp output file?
    final String sourceFile = filename;
    final String destinationFile = GetTempDestinationFile();

    LoadImageConverters();/*from   w ww.  j a  va  2s .  c o  m*/
    if (ChooseImageConversionOptions(false) == false)
        return false;

    final ProgressMonitor pm = new ProgressMonitor(null, translator.get("Converting"), "", 0, 100);
    pm.setProgress(0);
    pm.setMillisToPopup(0);

    final SwingWorker<Void, Void> s = new SwingWorker<Void, Void>() {
        @Override
        public Void doInBackground() {
            // read in image
            BufferedImage img;
            try {
                Log("<font color='green'>" + translator.get("Converting") + " " + destinationFile
                        + "</font>\n");
                // convert with style
                img = ImageIO.read(new File(sourceFile));
                int style = GetDrawStyle();
                Filter f = image_converters.get(style);
                TabToLog();
                f.SetParent(this);
                f.SetProgressMonitor(pm);
                f.SetDestinationFile(destinationFile);
                f.Convert(img);
                TabToDraw();
                previewPane.ZoomToFitPaper();
            } catch (IOException e) {
                Log("<font color='red'>" + translator.get("Failed") + e.getLocalizedMessage() + "</font>\n");
                recentFiles.remove(sourceFile);
                updateMenuBar();
            }

            pm.setProgress(100);
            return null;
        }

        @Override
        public void done() {
            pm.close();
            Log("<font color='green'>" + translator.get("Finished") + "</font>\n");
            PlayConversionFinishedSound();
            LoadGCode(destinationFile);
        }
    };

    s.addPropertyChangeListener(new PropertyChangeListener() {
        // Invoked when task's progress property changes.
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == evt.getPropertyName()) {
                int progress = (Integer) evt.getNewValue();
                pm.setProgress(progress);
                String message = String.format("%d%%.\n", progress);
                pm.setNote(message);
                if (s.isDone()) {
                    Log("<font color='green'>" + translator.get("Finished") + "</font>\n");
                } else if (s.isCancelled() || pm.isCanceled()) {
                    if (pm.isCanceled()) {
                        s.cancel(true);
                    }
                    Log("<font color='green'>" + translator.get("Cancelled") + "</font>\n");
                }
            }
        }
    });

    s.execute();

    return true;
}

From source file:de.cismet.cids.custom.objecteditors.wunda_blau.WebDavPicturePanel.java

/**
 * DOCUMENT ME!//from w  w  w . j  av a2 s.  co m
 *
 * @param   fileName  DOCUMENT ME!
 *
 * @return  DOCUMENT ME!
 *
 * @throws  Exception  DOCUMENT ME!
 */
private BufferedImage downloadImageFromWebDAV(final String fileName) throws Exception {
    final InputStream iStream = webdavHelper.getFileFromWebDAV(fileName, webdavDirectory,
            getConnectionContext());
    try {
        final ImageInputStream iiStream = ImageIO.createImageInputStream(iStream);
        final Iterator<ImageReader> itReader = ImageIO.getImageReaders(iiStream);
        if (itReader.hasNext()) {
            final ImageReader reader = itReader.next();
            final ProgressMonitor monitor = new ProgressMonitor(this, "Bild wird bertragen...", "", 0, 100);
            //            monitor.setMillisToPopup(500);
            reader.addIIOReadProgressListener(new IIOReadProgressListener() {

                @Override
                public void sequenceStarted(final ImageReader source, final int minIndex) {
                }

                @Override
                public void sequenceComplete(final ImageReader source) {
                }

                @Override
                public void imageStarted(final ImageReader source, final int imageIndex) {
                    monitor.setProgress(monitor.getMinimum());
                }

                @Override
                public void imageProgress(final ImageReader source, final float percentageDone) {
                    if (monitor.isCanceled()) {
                        try {
                            iiStream.close();
                        } catch (final IOException ex) {
                            // NOP
                        }
                    } else {
                        monitor.setProgress(Math.round(percentageDone));
                    }
                }

                @Override
                public void imageComplete(final ImageReader source) {
                    monitor.setProgress(monitor.getMaximum());
                }

                @Override
                public void thumbnailStarted(final ImageReader source, final int imageIndex,
                        final int thumbnailIndex) {
                }

                @Override
                public void thumbnailProgress(final ImageReader source, final float percentageDone) {
                }

                @Override
                public void thumbnailComplete(final ImageReader source) {
                }

                @Override
                public void readAborted(final ImageReader source) {
                    monitor.close();
                }
            });

            final ImageReadParam param = reader.getDefaultReadParam();
            reader.setInput(iiStream, true, true);
            final BufferedImage result;
            try {
                result = reader.read(0, param);
            } finally {
                reader.dispose();
                iiStream.close();
            }
            return result;
        } else {
            return null;
        }
    } finally {
        IOUtils.closeQuietly(iStream);
    }
}

From source file:cool.pandora.modeller.ui.jpanel.base.BagView.java

/**
 * statusBarBegin.//  www .  j  a v a  2 s  .  c o m
 *
 * @param progress          Progress
 * @param message           String
 * @param activityMonitored String
 */
public void statusBarBegin(final Progress progress, final String message, final String activityMonitored) {
    BusyIndicator.showAt(Application.instance().getActiveWindow().getControl());
    task = new LongTask();
    task.setActivityMonitored(activityMonitored);
    task.setProgress(progress);

    timer.addActionListener(new TimerListener());

    progressMonitor = new ProgressMonitor(this.getControl(), message, "Preparing the " + "operation...", 0, 1);
    progressMonitor.setMillisToDecideToPopup(ONE_SECOND);
    task.setMonitor(progressMonitor);

    task.go();
    timer.start();
}

From source file:com.diversityarrays.kdxplore.trialmgr.trait.TraitExplorerPanel.java

private void doImportTraitsFileImpl(File file) {
    Context context = KDSmartApplication.getInstance();
    final ProgressMonitor monitor = new ProgressMonitor(TraitExplorerPanel.this, "Loading", "", 0, 100);
    ProgressReporter progressReporter = new ProgressReporter() {

        @Override/*  w  ww  . ja  v  a2  s .c  om*/
        public void setProgressNote(String note) {
            monitor.setNote(note);
        }

        @Override
        public void setProgressMaximum(int max) {
            monitor.setMaximum(max);
        }

        @Override
        public void setProgressCount(int count) {
            monitor.setProgress(count);
        }

        @Override
        public void dismissProgress() {
            monitor.close();
        }
    };

    try {
        Either<ImportError, TraitImportTransactions> either = offlineData.getKdxploreDatabase()
                .getKDXploreKSmartDatabase().importTraitsFile(context, file, progressReporter);

        if (either.isLeft()) {
            ImportError ie = either.left();
            MsgBox.error(TraitExplorerPanel.this, ie.getMessage("Import Traits"), "Import Failed");
        } else {
            TraitImportTransactions tit = either.right();

            if (!tit.traitsToBeUpdated.isEmpty()) {

            }

            refreshTraitsTable();

            StringBuilder sb = new StringBuilder("Import Result");
            if (tit.nSkipped > 0) {
                sb.append("\nSkipped ").append(tit.nSkipped);
            }
            if (!tit.traitsToBeAdded.isEmpty()) {
                sb.append("\nAdded: ").append(tit.traitsToBeAdded.size());
            }
            if (!tit.traitsToBeUpdated.isEmpty()) {
                sb.append("\nUpdated: ").append(tit.traitsToBeUpdated.size());
            }
            MsgBox.info(TraitExplorerPanel.this, sb.toString(), "Import Complete");
        }
    } finally {
        progressReporter.dismissProgress();
    }
}

From source file:gov.noaa.ncdc.iosp.avhrr.util.AvhrrLevel1B2Netcdf.java

private void convertButtonActionPerformed(ActionEvent evt) {
    files = fm.getFilesToConvert();//from   www .  j  av  a 2 s .c o m
    if (files == null || files.size() == 0) {
        JOptionPane.showMessageDialog(this, "No valid files were selected!", "Message",
                JOptionPane.ERROR_MESSAGE);
    } else {
        List<String> options = determineOptions();
        activity = new NetcdfConverter(files, options, outdirText.getText());
        // launch progress dialog
        progressDialog = new ProgressMonitor(AvhrrLevel1B2Netcdf.this, "Converting Files....", null, -1,
                activity.getTotal() + 2);
        progressDialog.setMillisToDecideToPopup(0);
        activityMonitor.start();
        activity.start();
        // start timer
        convertButton.setEnabled(false);
    }
}