Example usage for java.awt Rectangle Rectangle

List of usage examples for java.awt Rectangle Rectangle

Introduction

In this page you can find the example usage for java.awt Rectangle Rectangle.

Prototype

public Rectangle(int x, int y, int width, int height) 

Source Link

Document

Constructs a new Rectangle whose upper-left corner is specified as (x,y) and whose width and height are specified by the arguments of the same name.

Usage

From source file:jhplot.HPlotChart.java

/**
 * Export graph into an image file. The the image format is given by
 * extension. "png", "jpg", "eps", "pdf", "svg". In case of "eps", "pdf" and
 * "svg", vector graphics is used.//from  w w  w.  j av  a2 s. c o  m
 * 
 * @param filename
 *            file name
 * @param width
 *            width
 * @param height
 *            hight
 */
public void export(String filename, int width, int height) {

    String fname = filename;
    String filetype = "pdf";
    int i = filename.lastIndexOf('.');
    if (i > 0) {
        filetype = fname.substring(i + 1);
    }

    try {
        if (filetype.equalsIgnoreCase("png")) {
            BufferedImage b = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = b.createGraphics();

            drawToGraphics2D(g, width, height);
            g.dispose();
            ImageIO.write(b, "png", new File(fname));
        } else if (filetype.equalsIgnoreCase("jpg") || filetype.equalsIgnoreCase("jpeg")) {
            BufferedImage b = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = b.createGraphics();
            drawToGraphics2D(g, width, height);
            g.dispose();
            ImageIO.write(b, "jpg", new File(fname));

            /*
             * } else if (filetype.equalsIgnoreCase("eps")) { try {
             * ImageType currentImageType = ImageType.EPS; Rectangle r = new
             * Rectangle (0, 0, width, height);
             * Export.exportComponent(getCanvasPanel(), r, new
             * File(filename), currentImageType); } catch (IOException e) {
             * e.printStackTrace(); } catch
             * (org.apache.batik.transcoder.TranscoderException e) {
             * e.printStackTrace(); }
             */

        } else if (filetype.equalsIgnoreCase("ps")) {
            try {
                ImageType currentImageType = ImageType.PS;
                Rectangle r = new Rectangle(0, 0, width, height);
                Export.exportComponent(cp, r, new File(filename), currentImageType);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (org.apache.batik.transcoder.TranscoderException e) {
                e.printStackTrace();
            }

        } else if (filetype.equalsIgnoreCase("eps")) {

            try {
                FileOutputStream outputStream = new FileOutputStream(fname);
                org.jibble.epsgraphics.EpsGraphics2D g = new org.jibble.epsgraphics.EpsGraphics2D(
                        "HChart canvas", outputStream, 0, 0, width, height);// #Create
                // a
                // new
                // document
                // with
                // bounding
                // box
                // 0 <=
                // x <=
                // 100
                // and
                // 0 <=
                // y <=
                // 100.
                drawToGraphics2D(g, width, height);
                g.flush();
                g.close();
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("Problem writing eps");
            }

        } else if (filetype.equalsIgnoreCase("pdf")) {

            try {
                FileOutputStream outputStream = new FileOutputStream(fname);
                com.lowagie.text.pdf.FontMapper mapper = new com.lowagie.text.pdf.DefaultFontMapper();
                com.lowagie.text.Rectangle pagesize = new com.lowagie.text.Rectangle(width, height);
                com.lowagie.text.Document document = new com.lowagie.text.Document(pagesize, 50, 50, 50, 50);
                try {
                    com.lowagie.text.pdf.PdfWriter writer = com.lowagie.text.pdf.PdfWriter.getInstance(document,
                            outputStream);
                    // document.addAuthor("JFreeChart");
                    // document.addSubject("Jylab");
                    document.open();
                    com.lowagie.text.pdf.PdfContentByte cb = writer.getDirectContent();
                    com.lowagie.text.pdf.PdfTemplate tp = cb.createTemplate(width, height);
                    Graphics2D g = tp.createGraphics(width, height, mapper);
                    // Rectangle2D r2D = new Rectangle2D.Double(0, 0, width,
                    // height);

                    drawToGraphics2D(g, width, height);
                    g.dispose();
                    cb.addTemplate(tp, 0, 0);

                } catch (com.lowagie.text.DocumentException de) {
                    System.err.println(de.getMessage());
                }
                document.close();
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("Cannot find itext library, cannot create pdf.");
            }

        } else if (filetype.equalsIgnoreCase("svg")) {

            try {

                // import org.apache.batik.dom.GenericDOMImplementation;
                // import org.apache.batik.svggen.SVGGraphics2D;

                org.w3c.dom.DOMImplementation domImpl = org.apache.batik.dom.GenericDOMImplementation
                        .getDOMImplementation();
                // Create an instance of org.w3c.dom.Document
                org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
                // Create an instance of the SVG Generator
                org.apache.batik.svggen.SVGGraphics2D svgGenerator = new org.apache.batik.svggen.SVGGraphics2D(
                        document);
                svgGenerator.setSVGCanvasSize(new Dimension(width, height));
                // set the precision to avoid a null pointer exception in
                // Batik 1.5
                svgGenerator.getGeneratorContext().setPrecision(6);
                // Ask the chart to render into the SVG Graphics2D
                // implementation

                drawToGraphics2D(svgGenerator, width, height);
                // chart.draw(svgGenerator, new Rectangle2D.Double(0, 0,
                // width, height), null);
                // Finally, stream out SVG to a file using UTF-8 character
                // to
                // byte encoding
                boolean useCSS = true;
                Writer out = new OutputStreamWriter(new FileOutputStream(new File(filename)), "UTF-8");
                svgGenerator.stream(out, useCSS);
                out.close();

            } catch (org.w3c.dom.DOMException e) {
                System.err.println("Problem writing to SVG");
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("Missing Batik libraries?");
            }

        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:fr.amap.commons.javafx.chart.ChartViewer.java

/**
 * A handler for the export to PDF option in the context menu.
 *//*from www . j a  v a2s.c  o m*/
private void handleExportToPDF() {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setSelectedExtensionFilter(
            new FileChooser.ExtensionFilter("Portable Document Format (PDF)", "pdf"));
    fileChooser.setTitle("Export to PDF");
    File file = fileChooser.showSaveDialog(stage);
    if (file != null) {

        try {

            CanvasPositionsAndSize canvasPositionAndSize = getCanvasPositionAndSize();

            PDDocument doc = new PDDocument();

            PDPage page = new PDPage(new PDRectangle((float) canvasPositionAndSize.totalWidth,
                    (float) canvasPositionAndSize.totalHeight));
            doc.addPage(page);

            BufferedImage image = new BufferedImage((int) canvasPositionAndSize.totalWidth,
                    (int) canvasPositionAndSize.totalHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = image.createGraphics();

            int index = 0;
            for (ChartCanvas canvas : chartCanvasList) {

                Rectangle2D rectangle2D = canvasPositionAndSize.positionsAndSizes.get(index);

                ((Drawable) canvas.chart).draw(g2, new Rectangle((int) rectangle2D.getX(),
                        (int) rectangle2D.getY(), (int) rectangle2D.getWidth(), (int) rectangle2D.getHeight()));
                index++;
            }

            PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, false);
            PDXObjectImage pdImage = new PDPixelMap(doc, image);
            contentStream.drawImage(pdImage, 0, 0);

            PDPageContentStream cos = new PDPageContentStream(doc, page);
            cos.drawXObject(pdImage, 0, 0, pdImage.getWidth(), pdImage.getHeight());
            cos.close();

            doc.save(file);

        } catch (IOException | COSVisitorException ex) {
            Logger.getLogger(ChartViewer.class.getName()).log(Level.SEVERE, null, ex);
        }
        /*ExportUtils.writeAsPDF(this.chart, (int)canvas.getWidth(),
        (int)canvas.getHeight(), file);*/

        /*ExportUtils.writeAsPDF(this.chart, (int)canvas.getWidth(),
                (int)canvas.getHeight(), file);*/
    }
}

From source file:org.eurocarbdb.application.glycoworkbench.plugin.reporting.ProfilesComparisonReportChartCanvas.java

private Rectangle getChartArea(double scale) {
    int chart_width = Math.max(CHART_WIDTH, CHART_WIDTH_TICK * theDocument.getNoRows());
    return new Rectangle((int) (DRAW_X_MARGIN + scale * CHART_X_MARGIN),
            (int) (DRAW_Y_MARGIN + scale * CHART_Y_MARGIN), (int) (scale * chart_width),
            (int) (scale * CHART_HEIGHT));
}

From source file:fr.avianey.androidsvgdrawable.SvgDrawablePlugin.java

/**
 * Extract the viewbox of the input SVG/*  w w w  . j  a v a 2 s.c om*/
 * @param svg
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
@VisibleForTesting
Rectangle extractSVGBounds(QualifiedResource svg) throws MalformedURLException, IOException {
    // check <svg> attributes first : x, y, width, height
    SVGDocument svgDocument = getSVGDocument(svg);
    SVGSVGElement svgElement = svgDocument.getRootElement();
    if (svgElement.getAttributeNode("width") != null && svgElement.getAttribute("height") != null) {

        UserAgent userAgent = new DensityAwareUserAgent(svg.getDensity().getDpi());
        UnitProcessor.Context context = org.apache.batik.bridge.UnitProcessor
                .createContext(new BridgeContext(userAgent), svgElement);

        float width = svgLengthInPixels(svgElement.getWidth().getBaseVal(), context);
        float height = svgLengthInPixels(svgElement.getHeight().getBaseVal(), context);
        float x = 0;
        float y = 0;
        // check x and y attributes
        if (svgElement.getX() != null && svgElement.getX().getBaseVal() != null) {
            x = svgLengthInPixels(svgElement.getX().getBaseVal(), context);
        }
        if (svgElement.getY() != null && svgElement.getY().getBaseVal() != null) {
            y = svgLengthInPixels(svgElement.getY().getBaseVal(), context);
        }

        return new Rectangle((int) Math.floor(x), (int) Math.floor(y), (int) Math.ceil(width),
                (int) Math.ceil(height));
    }

    // use computed bounds
    getLog().warn(
            "Take time to fix desired width and height attributes of the root <svg> node for this file... "
                    + "ROI will be computed by magic using Batik " + parameters.getSvgBoundsType().name()
                    + " bounds");
    return parameters.getSvgBoundsType().getBounds(getGraphicsNode(svgDocument, svg.getDensity().getDpi()));
}

From source file:gdsc.smlm.ij.plugins.DensityImage.java

/**
 * Crop the results to the ROI. Add a border using the sampling radius so that counts do not have to be approximated
 * (i.e. all spots around the edge of the ROI will have a complete image to sample from). The results are modified
 * in place./*from  w  ww  .j  av a 2 s . c  o  m*/
 * 
 * @param results
 * @param isWithin
 *            Set to true if the added border is within the original bounds (i.e. no adjustment for missing counts
 *            is required)
 * @return
 */
private MemoryPeakResults cropWithBorder(MemoryPeakResults results, boolean[] isWithin) {
    isWithin[0] = false;
    if (roiBounds == null)
        return results;

    // Adjust bounds relative to input results image:
    // Use the ROI relative to the frame the ROI is drawn on. 
    // Map those fractional coordinates back to the original data bounds.
    Rectangle bounds = results.getBounds();
    double xscale = (double) roiImageWidth / bounds.width;
    double yscale = (double) roiImageHeight / bounds.height;

    // Compute relative to the results bounds (if present)
    scaledRoiMinX = bounds.x + roiBounds.x / xscale;
    scaledRoiMaxX = scaledRoiMinX + roiBounds.width / xscale;
    scaledRoiMinY = bounds.y + roiBounds.y / yscale;
    scaledRoiMaxY = scaledRoiMinY + roiBounds.height / yscale;

    // Allow for the border
    final float minX = (int) (scaledRoiMinX - radius);
    final float maxX = (int) Math.ceil(scaledRoiMaxX + radius);
    final float minY = (int) (scaledRoiMinY - radius);
    final float maxY = (int) Math.ceil(scaledRoiMaxY + radius);

    // Create a new set of results within the bounds
    MemoryPeakResults newResults = new MemoryPeakResults();
    newResults.begin();
    for (PeakResult peakResult : results.getResults()) {
        float x = peakResult.params[Gaussian2DFunction.X_POSITION];
        float y = peakResult.params[Gaussian2DFunction.Y_POSITION];
        if (x < minX || x > maxX || y < minY || y > maxY)
            continue;
        newResults.add(peakResult);
    }
    newResults.end();
    newResults.copySettings(results);
    newResults.setBounds(new Rectangle((int) minX, (int) minY, (int) (maxX - minX), (int) (maxY - minY)));
    isWithin[0] = minX >= bounds.x && minY >= bounds.y && maxX <= (bounds.x + bounds.width)
            && maxY <= (bounds.y + bounds.height);
    return newResults;
}

From source file:com.projity.pm.graphic.network.NetworkRenderer.java

public void paint(Graphics g, Rectangle visibleBounds) {
    Graphics2D g2 = (Graphics2D) g;

    Rectangle clipBounds = g2.getClipBounds();
    Rectangle svgClip = clipBounds;
    if (clipBounds == null) {
        clipBounds = getGraphInfo().getDrawingBounds();
        //start at O,O because it's already translated
        if (visibleBounds == null)
            clipBounds = new Rectangle(0, 0, clipBounds.width, clipBounds.height);
        else {/*from w ww.j  av  a  2  s  . c o  m*/
            clipBounds = visibleBounds;
            g2.setClip(clipBounds);
        }
    }
    //Modif for offline graphics

    GraphicDependency dependency;
    for (Iterator i = getDependenciesIterator(); i.hasNext();) {
        dependency = (GraphicDependency) i.next();
        paintLink(g2, dependency);
    }

    GraphicNode node;
    Rectangle bounds;
    for (ListIterator i = graphInfo.getCache().getIterator(); i.hasNext();) {
        node = (GraphicNode) i.next();
        bounds = getBounds(node);
        if (bounds == null)
            continue;
        if (clipBounds.intersects(bounds))
            paintNode(g2, node);
    }

    if (visibleBounds != null)
        g2.setClip(svgClip);
}

From source file:edu.umd.cfar.lamp.viper.geometry.BoundingBox.java

/**
 * Sets <code>this</code> to refer to only the given bounding box.
 * /*from w w w .ja va2  s. co m*/
 * @param x
 *            the x coordinate of the box origin point
 * @param y
 *            the y coordinate of the box origin point
 * @param width
 *            the width of the box
 * @param height
 *            the height of the box
 */
public void set(int x, int y, int width, int height) {
    rect = new Rectangle(x, y, width, height);
    initPoly();
}

From source file:edu.harvard.mcz.imagecapture.encoder.UnitTrayLabelBrowser.java

private JMenuItem getJMenuItemAddRow() {
    if (jMenuItemAddRow == null) {
        jMenuItemAddRow = new JMenuItem();
        jMenuItemAddRow.setText("Add Blank Row");
        jMenuItemAddRow.setMnemonic(KeyEvent.VK_D);
        jMenuItemAddRow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                addRow();/*w  w w .j  a v a 2 s  .c  o m*/

                //jTable.scrollRectToVisible(jTable.getCellRect(jTable.getRowCount(), 1, false));
                //jTable.editCellAt(jTable.getRowCount(), 1);
                //jScrollPane.getVerticalScrollBar().setValue(jScrollPane.getVerticalScrollBar().getMaximum());
                //jScrollPane.getViewport().invalidate();
                //jScrollPane.getViewport().validate();
                //jScrollPane.getVerticalScrollBar().setValue(jScrollPane.getVerticalScrollBar().getMaximum());

                Rectangle newCell = new Rectangle(1, jTable.getRowHeight() * (jTable.getRowCount()), 10,
                        jTable.getRowHeight());
                //jTable.scrollRectToVisible(newCell);
            }
        });
    }
    return jMenuItemAddRow;
}

From source file:de.fhg.igd.mapviewer.waypoints.CustomWaypointPainter.java

/**
 * Find the way-points in a given rectangular area
 * /*w w  w. j  av  a 2 s  . c  o m*/
 * @param rect the area
 * @return the way-points in the area
 */
public Set<W> findWaypoints(Rectangle rect) {
    Rectangle viewPort = getMapKit().getMainMap().getViewportBounds();

    final Rectangle worldRect = new Rectangle(viewPort.x + rect.x, viewPort.y + rect.y, rect.width,
            rect.height);

    final int zoom = getMapKit().getMainMap().getZoom();
    final PixelConverter converter = getMapKit().getMainMap().getTileFactory().getTileProvider().getConverter();

    final GeoPosition topLeft = converter.pixelToGeo(new Point(worldRect.x, worldRect.y), zoom);
    final GeoPosition bottomRight = converter
            .pixelToGeo((new Point(worldRect.x + worldRect.width, worldRect.y + worldRect.height)), zoom);

    return findWaypoints(topLeft, bottomRight, worldRect, converter, zoom);
}

From source file:com.t_oster.visicut.misc.Helper.java

public static Rectangle toRect(Rectangle2D src) {
    if (src == null) {
        return new Rectangle(0, 0, 0, 0);
    }//w w w .  j  av a  2  s . c  o  m
    return new Rectangle((int) src.getX(), (int) src.getY(), (int) src.getWidth(), (int) src.getHeight());
}