Example usage for javax.swing ProgressMonitor setMaximum

List of usage examples for javax.swing ProgressMonitor setMaximum

Introduction

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

Prototype

public void setMaximum(int m) 

Source Link

Document

Specifies the maximum value.

Usage

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();/*from  w w  w  . jav  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.monead.semantic.workbench.SemanticWorkbench.java

/**
 * Attempt to load a set of assertions with the supplied format (e.g. N3,
 * RDF/XML, etc)//  w  w  w  .j ava  2  s .c  o m
 * 
 * @param format
 *          The format to use, must be a value in the array FORMATS
 * 
 * @throws IOException
 *           If the file cannot be read
 */
private void tryFormat(String format) throws IOException {
    InputStream inputStream = null;

    try {
        LOGGER.debug("Start " + reasoningLevel.getSelectedItem().toString()
                + " model load and setup with format " + format);

        if (hasIncompleteAssertionsInput) {
            inputStream = new ProgressMonitorInputStream(this,
                    "Reading file " + rdfFileSource.getAbsolutePath(), rdfFileSource.getInputStream());

            if (rdfFileSource.isUrl()) {
                final ProgressMonitor pm = ((ProgressMonitorInputStream) inputStream).getProgressMonitor();
                pm.setMaximum((int) rdfFileSource.length());
            }
            LOGGER.debug("Using a ProgressMonitorInputStream");
        } else {
            inputStream = new ByteArrayInputStream(assertionsInput.getText().getBytes("UTF-8"));
        }

        ontModel = createModel((ReasonerSelection) reasoningLevel.getSelectedItem());
        LOGGER.debug("Begin loading model");
        ontModel.read(inputStream, null, format.toUpperCase());

        LOGGER.debug(reasoningLevel.getSelectedItem().toString() + " model load and setup completed");
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Throwable throwable) {
                LOGGER.error("Error closing input file", throwable);
            }
        }
    }
}

From source file:com.monead.semantic.workbench.SemanticWorkbench.java

/**
 * Load the provided file as an ontology replacing any assertions currently
 * in the assertions text area./*w  w w  .j a  v  a 2 s  .c  o  m*/
 * 
 * @return The message to be presented on the status line
 */
private String loadOntologyFile() {
    final int chunkSize = 32000;
    StringBuilder allData;
    char[] chunk;
    long totalBytesRead = 0;
    int chunksRead = 0;
    int maxChunks;
    int bytesRead = -1;
    ProgressMonitor monitor = null;
    Reader reader = null;
    String message;
    boolean loadCanceled = false;

    if (rdfFileSource.isFile()) {
        lastDirectoryUsed = rdfFileSource.getBackingFile().getParentFile();
    }

    assertionsInput.setText("");
    invalidateModel(false);

    allData = new StringBuilder();
    chunk = new char[chunkSize];

    setStatus("Loading file " + rdfFileSource.getAbsolutePath());

    if (rdfFileSource.length() > 0 && rdfFileSource.length() < MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA) {
        maxChunks = (int) (rdfFileSource.length() / chunkSize);
    } else {
        maxChunks = (int) (MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA / chunkSize);
    }

    if (rdfFileSource.length() % chunkSize > 0) {
        ++maxChunks;
    }

    // Assume the file can be loaded
    hasIncompleteAssertionsInput = false;

    monitor = new ProgressMonitor(this, "Loading assertions from " + rdfFileSource.getName(), "0 bytes read", 0,
            maxChunks);

    try {
        reader = new InputStreamReader(rdfFileSource.getInputStream());
        while (!loadCanceled && (rdfFileSource.isUrl() || chunksRead < maxChunks)
                && (bytesRead = reader.read(chunk)) > -1) {
            totalBytesRead += bytesRead;

            chunksRead = (int) (totalBytesRead / chunk.length);

            if (chunksRead < maxChunks) {
                allData.append(chunk, 0, bytesRead);
            }

            if (chunksRead >= maxChunks) {
                monitor.setMaximum(chunksRead + 1);
            }

            monitor.setProgress(chunksRead);
            monitor.setNote("Read " + INTEGER_COMMA_FORMAT.format(totalBytesRead)
                    + (rdfFileSource.isFile() ? " of " + INTEGER_COMMA_FORMAT.format(rdfFileSource.length())
                            : " bytes")
                    + (chunksRead >= maxChunks ? " (Determining total file size)" : ""));

            loadCanceled = monitor.isCanceled();
        }

        if (!loadCanceled && rdfFileSource.isUrl()) {
            rdfFileSource.setLength(totalBytesRead);
        }

        if (!loadCanceled && rdfFileSource.length() > MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA) {
            // The entire file was not loaded
            hasIncompleteAssertionsInput = true;
        }

        if (hasIncompleteAssertionsInput) {
            StringBuilder warningMessage;

            warningMessage = new StringBuilder();
            warningMessage.append("The file is too large to display. However the entire file will be loaded\n");
            warningMessage.append("into the model when it is built.\n\nDisplay size limit (bytes): ");
            warningMessage.append(INTEGER_COMMA_FORMAT.format(MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA));
            if (rdfFileSource.isFile()) {
                warningMessage.append("\nFile size (bytes):");
                warningMessage.append(INTEGER_COMMA_FORMAT.format(rdfFileSource.length()));
            }
            warningMessage.append("\n\n");
            warningMessage.append("Note that the assersions text area will not permit editing\n");
            warningMessage.append("of the partially loaded file and the 'save assertions' menu\n");
            warningMessage.append("option will be disabled. These limitations are enabled\n");
            warningMessage.append("to prevent the accidental loss of information from the\n");
            warningMessage.append("source assertions file.");

            JOptionPane.showMessageDialog(this, warningMessage.toString(), "Max Display Size Reached",
                    JOptionPane.WARNING_MESSAGE);

            // Add text to the assertions text area to highlight the fact that the
            // entire file was not loaded into the text area
            allData.insert(0,
                    "# First " + INTEGER_COMMA_FORMAT.format(MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA)
                            + " of " + INTEGER_COMMA_FORMAT.format(rdfFileSource.length())
                            + " bytes displayed\n\n");
            allData.insert(0, "# INCOMPLETE VERSION of the file: " + rdfFileSource.getAbsolutePath() + "\n");
            allData.append("\n\n# INCOMPLETE VERSION of the file: " + rdfFileSource.getAbsolutePath() + "\n");
            allData.append("# First " + INTEGER_COMMA_FORMAT.format(MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA)
                    + " of " + INTEGER_COMMA_FORMAT.format(rdfFileSource.length()) + " bytes displayed\n");
        }

        // Set the loaded assertions into the text area, cleaning up Windows \r\n
        // endings, if found
        if (!loadCanceled) {
            assertionsInput.setText(allData.toString().replaceAll("\r\n", "\n"));
            assertionsInput.setSelectionEnd(0);
            assertionsInput.setSelectionStart(0);
            assertionsInput.moveCaretPosition(0);
            assertionsInput.scrollRectToVisible(new Rectangle(0, 0, 1, 1));

            message = "Loaded file" + (hasIncompleteAssertionsInput ? " (incomplete)" : "") + ": "
                    + rdfFileSource.getName();
            addRecentAssertedTriplesFile(rdfFileSource);

            // Select the assertions tab
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    tabbedPane.setSelectedIndex(TAB_NUMBER_ASSERTIONS);
                    setFocusOnCorrectTextArea();
                }
            });
        } else {
            message = "Assertions file load canceled by user";
        }
    } catch (Throwable throwable) {
        setStatus("Unable to load file: " + rdfFileSource.getName());
        JOptionPane.showMessageDialog(this, "Error: Unable to read file\n\n" + rdfFileSource.getAbsolutePath()
                + "\n\n" + throwable.getMessage(), "Error Reading File", JOptionPane.ERROR_MESSAGE);
        LOGGER.error("Unable to load the file: " + rdfFileSource.getAbsolutePath(), throwable);
        message = "Unable to load the file: " + rdfFileSource.getAbsolutePath();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Throwable throwable) {
                LOGGER.error("Unable to close input file", throwable);
            }
        }

        if (monitor != null) {
            monitor.close();
        }
    }

    return message;
}

From source file:org.silverpeas.openoffice.windows.webdav.WebdavManager.java

/**
 * Get the ressource from the webdav server.
 *
 * @param uri the uri to the ressource./*www. jav a2  s .c  o m*/
 * @param lockToken the current lock token.
 * @return the path to the saved file on the filesystem.
 * @throws IOException
 */
public String getFile(URI uri, String lockToken) throws IOException {
    GetMethod method = executeGetFile(uri);
    String fileName = uri.getPath();
    fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
    fileName = URLDecoder.decode(fileName, "UTF-8");
    UIManager.put("ProgressMonitor.progressText", MessageUtil.getMessage("download.file.title"));
    ProgressMonitorInputStream is = new ProgressMonitorInputStream(null,
            MessageUtil.getMessage("downloading.remote.file") + ' ' + fileName,
            new BufferedInputStream(method.getResponseBodyAsStream()));
    fileName = fileName.replace(' ', '_');
    ProgressMonitor monitor = is.getProgressMonitor();
    monitor.setMaximum(new Long(method.getResponseContentLength()).intValue());
    monitor.setMillisToDecideToPopup(0);
    monitor.setMillisToPopup(0);
    File tempDir = new File(System.getProperty("java.io.tmpdir"), "silver-" + System.currentTimeMillis());
    tempDir.mkdirs();
    File tmpFile = new File(tempDir, fileName);
    FileOutputStream fos = new FileOutputStream(tmpFile);
    byte[] data = new byte[64];
    int c;
    try {
        while ((c = is.read(data)) > -1) {
            fos.write(data, 0, c);
        }
    } catch (InterruptedIOException ioinex) {
        logger.log(Level.INFO, "{0} {1}",
                new Object[] { MessageUtil.getMessage("info.user.cancel"), ioinex.getMessage() });
        unlockFile(uri, lockToken);
        System.exit(0);
    } finally {
        fos.close();
    }
    return tmpFile.getAbsolutePath();
}

From source file:pt.lsts.neptus.plugins.bathym.XyzExporter.java

@Override
public String process(IMraLogGroup source, ProgressMonitor pmonitor) {
    pmonitor.setMaximum(100);
    PluginUtils.editPluginProperties(this, true);
    this.pmonitor = pmonitor;
    this.pmonitor.setMillisToDecideToPopup(0);

    this.pmonitor.setProgress(0);

    finder = TidePredictionFactory.create(source);
    if (finder == null)
        tideCorrection = false;/*from   ww  w  .j  ava2  s. c  o  m*/

    try {
        writer = new BufferedWriter(new FileWriter(file));

        // Writing header
        writer.write(COMMENT_STRING + "XYZ Data" + LINE_ENDING);
        double startTimeSeconds = source.getLsfIndex().getStartTime();
        writer.write(COMMENT_STRING + "Date of data: "
                + DateTimeUtil.dateFormatterUTC.format(new Date((long) (startTimeSeconds * 1E3)))
                + LINE_ENDING);
        writer.write(COMMENT_STRING + "Tide corrected: "
                + (tideCorrection ? "yes (" + finder.getName() + ")" : "no") + LINE_ENDING);

        // Data source info
        String dataSource = "";
        if (exportEstimatedState)
            dataSource = "navigation";
        if (exportMultibeam)
            dataSource += (dataSource.isEmpty() ? "" : ", ") + "multibeam";
        if (exportDistance)
            dataSource += (dataSource.isEmpty() ? "" : ", ") + "dvl";
        writer.write(COMMENT_STRING + "Data source: " + dataSource + LINE_ENDING);
        writer.write(COMMENT_STRING + LINE_ENDING);

        writer.write(COMMENT_STRING + "Longitude, Latitude, Depth" + LINE_ENDING);
        writer.write(COMMENT_STRING + "(decimal degrees, decimal degrees, meters)" + LINE_ENDING);
    } catch (Exception e) {
        e.printStackTrace();
        return I18n.textf("%name while trying to write to file: %message.", e.getClass().getSimpleName(),
                e.getMessage());
    }

    this.pmonitor.setProgress(10);

    if (exportEstimatedState) {
        pmonitor.setNote(I18n.text("Processing EstimatedState data"));
        processEstimatedStates(source);
    }

    this.pmonitor.setProgress(30);
    if (exportMultibeam) {
        pmonitor.setNote(I18n.text("Processing Multibeam data"));
        processMultibeam(source);
    }

    this.pmonitor.setProgress(60);
    if (exportDistance) {
        pmonitor.setNote(I18n.text("Processing DVL data"));
        processDvl(source);
    }

    this.pmonitor.setProgress(80);
    try {
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    String outputPath = file.getName();
    if (compressOutput) {
        this.pmonitor.setProgress(90);
        pmonitor.setNote(I18n.text("Compressing output"));
        ZipUtils.zipDir(file.getAbsolutePath() + ".zip", file.getAbsolutePath());
        outputPath += ".zip";
        pmonitor.setNote("Deleting file");
        FileUtils.deleteQuietly(file);
    }

    this.pmonitor.setProgress(100);

    return I18n.textf("File written to %file.", outputPath);
}