Example usage for java.awt Graphics2D translate

List of usage examples for java.awt Graphics2D translate

Introduction

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

Prototype

public abstract void translate(double tx, double ty);

Source Link

Document

Concatenates the current Graphics2D Transform with a translation transform.

Usage

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

protected void paintComponent(Graphics g) {

    // prepare graphic object
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    // set clipping area
    if (is_printing) {
        g2d.translate(-draw_area.x, -draw_area.y);
        g2d.setClip(draw_area);/*from  w  w  w . ja va  2  s .  co  m*/
    }

    //paint canvas background
    if (!is_printing) {
        g2d.setColor(getBackground());
        g2d.fillRect(0, 0, getWidth(), getHeight());
    }

    // paint white background on drawing area    
    g2d.setColor(Color.white);
    g2d.fillRect(draw_area.x, draw_area.y, draw_area.width, draw_area.height);
    if (!is_printing) {
        g2d.setColor(Color.black);
        g2d.draw(draw_area);
    }

    // paint
    paintChart(g2d);
    paintAnnotations(g2d);

    // dispose graphic object
    g2d.dispose();

    if (!is_printing) {
        if (first_time) {
            if (first_time_init_pos)
                placeStructures(true);
            else
                theDocument.fireDocumentInit();
            first_time = false;
        } else
            revalidate();
    }

}

From source file:convcao.com.caoAgent.convcaoNeptusInteraction.java

@Override
public void paint(Graphics2D g, StateRenderer2D renderer) {
    Point2D center = renderer.getScreenPosition(coords.squareCenter);
    double width = renderer.getZoom() * coords.cellWidth * coords.numCols;
    double height = renderer.getZoom() * coords.cellWidth * coords.numRows;
    g.setColor(new Color(0, 0, 255, 64));
    g.translate(center.getX(), center.getY());
    g.rotate(-renderer.getRotation());//from  ww w.j  a v a  2 s  .c  om
    g.fill(new Rectangle2D.Double(-width / 2, -height / 2, width, height));
    g.rotate(renderer.getRotation());
    g.translate(-center.getX(), -center.getY());

    if (!active)
        return;

    g.setColor(Color.orange);
    int pos = 50;
    for (String v : nameTable.values()) {
        g.drawString(v + ": " + depths.get(v) + "m", 15, pos);
        pos += 20;
    }

    for (String vehicle : nameTable.values()) {
        LocationType src = positions.get(vehicle);
        LocationType dst = destinations.get(vehicle);

        if (!arrived.get(vehicle))
            g.setColor(Color.red.darker());
        else
            g.setColor(Color.green.darker());
        float dash[] = { 4.0f };
        g.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 5.0f, dash, 0.0f));
        g.draw(new Line2D.Double(renderer.getScreenPosition(src), renderer.getScreenPosition(dst)));

        Point2D dstPt = renderer.getScreenPosition(dst);

        if (!arrived.get(vehicle))
            g.setColor(Color.red.darker());
        else
            g.setColor(Color.green.darker());

        g.fill(new Ellipse2D.Double(dstPt.getX() - 4, dstPt.getY() - 4, 8, 8));
    }
}

From source file:edu.umn.cs.spatialHadoop.operations.PyramidPlot.java

private static void plotLocal(Path inFile, Path outFile, OperationsParams params) throws IOException {
    int tileWidth = params.getInt("tilewidth", 256);
    int tileHeight = params.getInt("tileheight", 256);

    Color strokeColor = params.getColor("color", Color.BLACK);

    String hdfDataset = (String) params.get("dataset");
    Shape shape = hdfDataset != null ? new NASARectangle() : (Shape) params.getShape("shape", null);
    Shape plotRange = params.getShape("rect", null);

    String valueRangeStr = (String) params.get("valuerange");
    MinMax valueRange;//from  www .j av  a 2  s.co m
    if (valueRangeStr == null) {
        valueRange = null;
    } else {
        String[] parts = valueRangeStr.split(",");
        valueRange = new MinMax(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
    }

    InputSplit[] splits;
    FileSystem inFs = inFile.getFileSystem(params);
    FileStatus inFStatus = inFs.getFileStatus(inFile);
    if (inFStatus != null && !inFStatus.isDir()) {
        // One file, retrieve it immediately.
        // This is useful if the input is a hidden file which is automatically
        // skipped by FileInputFormat. We need to plot a hidden file for the case
        // of plotting partition boundaries of a spatial index
        splits = new InputSplit[] { new FileSplit(inFile, 0, inFStatus.getLen(), new String[0]) };
    } else {
        JobConf job = new JobConf(params);
        ShapeInputFormat<Shape> inputFormat = new ShapeInputFormat<Shape>();
        ShapeInputFormat.addInputPath(job, inFile);
        splits = inputFormat.getSplits(job, 1);
    }

    boolean vflip = params.is("vflip");

    Rectangle fileMBR;
    if (plotRange != null) {
        fileMBR = plotRange.getMBR();
    } else if (hdfDataset != null) {
        // Plotting a NASA file
        fileMBR = new Rectangle(-180, -90, 180, 90);
    } else {
        fileMBR = FileMBR.fileMBR(inFile, params);
    }

    boolean keepAspectRatio = params.is("keep-ratio", true);
    if (keepAspectRatio) {
        // Adjust width and height to maintain aspect ratio
        if (fileMBR.getWidth() > fileMBR.getHeight()) {
            fileMBR.y1 -= (fileMBR.getWidth() - fileMBR.getHeight()) / 2;
            fileMBR.y2 = fileMBR.y1 + fileMBR.getWidth();
        } else {
            fileMBR.x1 -= (fileMBR.getHeight() - fileMBR.getWidth() / 2);
            fileMBR.x2 = fileMBR.x1 + fileMBR.getHeight();
        }
    }

    if (hdfDataset != null) {
        // Collects some stats about the HDF file
        if (valueRange == null)
            valueRange = Aggregate.aggregate(new Path[] { inFile }, params);
        NASAPoint.minValue = valueRange.minValue;
        NASAPoint.maxValue = valueRange.maxValue;
        NASAPoint.setColor1(params.getColor("color1", Color.BLUE));
        NASAPoint.setColor2(params.getColor("color2", Color.RED));
        NASAPoint.gradientType = params.getGradientType("gradient", NASAPoint.GradientType.GT_HUE);
    }

    boolean adaptiveSampling = params.getBoolean("sample", false);

    int numLevels = params.getInt("numlevels", 7);

    float[] levelProb = new float[numLevels];
    double[] scale2 = new double[numLevels];
    double[] scale = new double[numLevels];
    levelProb[0] = params.getFloat(GeometricPlot.AdaptiveSampleRatio, 0.1f);
    // Size of the whole file in pixels at the f

    scale2[0] = (double) tileWidth * tileHeight / (fileMBR.getWidth() * fileMBR.getHeight());
    scale[0] = Math.sqrt(scale2[0]);
    for (int level = 1; level < numLevels; level++) {
        levelProb[level] = levelProb[level - 1] * 4;
        scale2[level] = scale2[level - 1] * (1 << level) * (1 << level);
        scale[level] = scale[level - 1] * (1 << level);
    }

    Map<TileIndex, BufferedImage> tileImages = new HashMap<PyramidPlot.TileIndex, BufferedImage>();

    Map<TileIndex, Graphics2D> tileGraphics = new HashMap<PyramidPlot.TileIndex, Graphics2D>();

    GridInfo bottomGrid = new GridInfo(fileMBR.x1, fileMBR.y1, fileMBR.x2, fileMBR.y2);
    bottomGrid.rows = bottomGrid.columns = (int) Math.round(Math.pow(2, numLevels - 1));

    TileIndex tileIndex = new TileIndex();
    boolean gradualFade = !(shape instanceof Point) && params.getBoolean("fade", false);

    for (InputSplit split : splits) {
        ShapeRecordReader<Shape> reader = new ShapeRecordReader<Shape>(params, (FileSplit) split);
        Rectangle cell = reader.createKey();
        while (reader.next(cell, shape)) {
            Rectangle shapeMBR = shape.getMBR();
            if (shapeMBR != null) {
                int min_level = 0;

                if (adaptiveSampling) {
                    // Special handling for NASA data
                    double p = Math.random();
                    // Skip levels that do not satisfy the probability
                    while (min_level < numLevels && p > levelProb[min_level])
                        min_level++;
                }

                java.awt.Rectangle overlappingCells = bottomGrid.getOverlappingCells(shapeMBR);
                for (tileIndex.level = numLevels - 1; tileIndex.level >= min_level; tileIndex.level--) {
                    if (gradualFade && !(shape instanceof Point)) {
                        double areaInPixels = (shapeMBR.getWidth() + shapeMBR.getHeight())
                                * scale[tileIndex.level];
                        if (areaInPixels < 1.0 && Math.round(areaInPixels * 255) < 1.0) {
                            // This shape can be safely skipped as it is too small to be plotted
                            return;
                        }
                    }

                    for (int i = 0; i < overlappingCells.width; i++) {
                        tileIndex.x = i + overlappingCells.x;
                        for (int j = 0; j < overlappingCells.height; j++) {
                            tileIndex.y = j + overlappingCells.y;
                            // Draw in image associated with this tile
                            Graphics2D g;
                            {
                                g = tileGraphics.get(tileIndex);
                                if (g == null) {
                                    TileIndex key = tileIndex.clone();
                                    BufferedImage image = new BufferedImage(tileWidth, tileHeight,
                                            BufferedImage.TYPE_INT_ARGB);
                                    if (tileImages.put(key, image) != null)
                                        throw new RuntimeException(
                                                "Error! Image is already there but graphics is not "
                                                        + tileIndex);

                                    Color bg_color = new Color(0, 0, 0, 0);

                                    try {
                                        g = image.createGraphics();
                                    } catch (Throwable e) {
                                        g = new SimpleGraphics(image);
                                    }
                                    g.setBackground(bg_color);
                                    g.clearRect(0, 0, tileWidth, tileHeight);
                                    g.setColor(strokeColor);
                                    // Coordinates of this tile in image coordinates
                                    g.translate(-(tileWidth * tileIndex.x), -(tileHeight * tileIndex.y));

                                    tileGraphics.put(key, g);
                                }
                            }

                            shape.draw(g, fileMBR, tileWidth * (1 << tileIndex.level),
                                    tileHeight * (1 << tileIndex.level), scale2[tileIndex.level]);
                        }
                    }
                    // Shrink overlapping cells to match the upper level
                    int updatedX1 = overlappingCells.x / 2;
                    int updatedY1 = overlappingCells.y / 2;
                    int updatedX2 = (overlappingCells.x + overlappingCells.width - 1) / 2;
                    int updatedY2 = (overlappingCells.y + overlappingCells.height - 1) / 2;
                    overlappingCells.x = updatedX1;
                    overlappingCells.y = updatedY1;
                    overlappingCells.width = updatedX2 - updatedX1 + 1;
                    overlappingCells.height = updatedY2 - updatedY1 + 1;
                }
            }
        }
        reader.close();
    }
    // Write image to output
    for (Map.Entry<TileIndex, Graphics2D> tileGraph : tileGraphics.entrySet()) {
        tileGraph.getValue().dispose();
    }
    FileSystem outFS = outFile.getFileSystem(params);
    for (Map.Entry<TileIndex, BufferedImage> tileImage : tileImages.entrySet()) {
        tileIndex = tileImage.getKey();
        BufferedImage image = tileImage.getValue();
        if (vflip) {
            AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
            tx.translate(0, -image.getHeight());
            AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
            image = op.filter(image, null);
            tileIndex.y = ((1 << tileIndex.level) - 1) - tileIndex.y;
        }
        Path imagePath = new Path(outFile, tileIndex.getImageFileName());
        FSDataOutputStream outStream = outFS.create(imagePath);
        ImageIO.write(image, "png", outStream);
        outStream.close();
    }
}

From source file:com.epiq.bitshark.ui.FrequencyDomainMouseMarker.java

/**
 * Draws the annotation./*from  ww  w. java  2s  .  com*/
 *
 * @param g2  the graphics device.
 * @param plot  the plot.
 * @param dataArea  the data area.
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param rendererIndex  the renderer index.
 * @param info  if supplied, this info object will be populated with
 *              entity information.
 */
@Override
public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis,
        int rendererIndex, PlotRenderingInfo info) {

    if (!visible) {
        return;
    }

    PlotOrientation orientation = plot.getOrientation();
    RectangleEdge domainEdge = Plot.resolveDomainAxisLocation(plot.getDomainAxisLocation(), orientation);
    RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation(plot.getRangeAxisLocation(), orientation);
    float j2DX = (float) domainAxis.valueToJava2D(this.x, dataArea, domainEdge);
    float j2DY = (float) rangeAxis.valueToJava2D(this.y, dataArea, rangeEdge);
    Rectangle2D displayArea = new Rectangle2D.Double(j2DX - this.displayWidth / 2.0,
            j2DY - this.displayHeight / 2.0, this.displayWidth, this.displayHeight);

    // here we change the AffineTransform so we can draw the annotation
    // to a larger area and scale it down into the display area
    // afterwards, the original transform is restored
    AffineTransform savedTransform = g2.getTransform();
    Rectangle2D drawArea = new Rectangle2D.Double(0.0, 0.0, this.displayWidth * this.drawScaleFactor,
            this.displayHeight * this.drawScaleFactor);

    g2.scale(1 / this.drawScaleFactor, 1 / this.drawScaleFactor);
    g2.translate((j2DX - this.displayWidth / 2.0) * this.drawScaleFactor,
            (j2DY - this.displayHeight / 2.0) * this.drawScaleFactor);
    draw(g2, drawArea);
    g2.setTransform(savedTransform);
    String toolTip = getToolTipText();
    String url = getURL();
    if (toolTip != null || url != null) {
        addEntity(info, displayArea, rendererIndex, toolTip, url);
    }

}

From source file:convcao.com.agent.ConvcaoNeptusInteraction.java

@Override
public void paint(Graphics2D g2, StateRenderer2D renderer) {
    Graphics2D g = (Graphics2D) g2.create();

    Point2D center = renderer.getScreenPosition(coords.squareCenter);
    double width = renderer.getZoom() * coords.cellWidth * coords.numCols;
    double height = renderer.getZoom() * coords.cellWidth * coords.numRows;
    g.setColor(new Color(0, 0, 255, 64));
    g.translate(center.getX(), center.getY());
    g.rotate(-renderer.getRotation());// www . java 2s.  c om
    g.fill(new Rectangle2D.Double(-width / 2, -height / 2, width, height));
    g.rotate(renderer.getRotation());
    g.translate(-center.getX(), -center.getY());

    if (!active) {
        g.dispose();
        return;
    }

    g.setColor(Color.orange);
    int pos = 50;
    for (String v : nameTable.values()) {
        g.drawString(v + ": " + depths.get(v) + "m", 15, pos);
        pos += 20;
    }

    for (String vehicle : nameTable.values()) {
        LocationType src = positions.get(vehicle);
        LocationType dst = destinations.get(vehicle);

        if (!arrived.get(vehicle))
            g.setColor(Color.red.darker());
        else
            g.setColor(Color.green.darker());
        float dash[] = { 4.0f };
        g.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 5.0f, dash, 0.0f));
        g.draw(new Line2D.Double(renderer.getScreenPosition(src), renderer.getScreenPosition(dst)));

        Point2D dstPt = renderer.getScreenPosition(dst);

        if (!arrived.get(vehicle))
            g.setColor(Color.red.darker());
        else
            g.setColor(Color.green.darker());

        g.fill(new Ellipse2D.Double(dstPt.getX() - 4, dstPt.getY() - 4, 8, 8));
    }

    g.dispose();
}

From source file:savant.view.swing.GraphPane.java

private void renderCurrentSelected(Graphics2D g2) {
    // Temporarily shift the origin
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.translate(0, getOffset());
    for (Track t : tracks) {
        if (t.getRenderer().hasMappedValues()) {
            List<Shape> currentSelected = t.getRenderer().getCurrentSelectedShapes(this);
            if (currentSelected.size() > 0) {
                boolean arcMode = t.getDrawingMode() == DrawingMode.ARC_PAIRED;
                for (Shape selectedShape : currentSelected) {
                    if (selectedShape != currentOverShape) {
                        if (arcMode) {
                            g2.setColor(Color.GREEN);
                            g2.draw(selectedShape);
                        } else {
                            //g2.setColor(Color.GREEN);
                            g2.setColor(new Color(0, 255, 0, 150));
                            g2.fill(selectedShape);
                            if (selectedShape.getBounds().getWidth() > 5) {
                                g2.setColor(Color.BLACK);
                                g2.draw(selectedShape);
                            }//www .jav  a2 s.  com
                        }
                    }
                }
            }
            break;
        }
    }
    if (currentOverShape != null) {
        if (tracks[0].getDrawingMode() == DrawingMode.ARC_PAIRED) {
            g2.setColor(Color.RED);
            g2.draw(currentOverShape);

            //get record pair
            BAMIntervalRecord rec1 = (BAMIntervalRecord) currentOverRecord;
            BAMIntervalRecord rec2 = ((BAMTrack) tracks[0]).getMate(rec1); //mate

            //render reads with mismatches
            ((BAMTrackRenderer) tracks[0].getRenderer()).renderReadsFromArc(g2, this, rec1, rec2, prevRange);

        } else {
            g2.setColor(new Color(255, 0, 0, 150));
            g2.fill(currentOverShape);
            if (currentOverShape.getBounds() != null && currentOverShape.getBounds().getWidth() > 5
                    && currentOverShape.getBounds().getHeight() > 3) {
                g2.setColor(Color.BLACK);
                g2.draw(currentOverShape);
            }
        }
    }
    //shift the origin back
    g2.translate(0, -getOffset());
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.graphics.internal.LogicalPageDrawable.java

/**
 * Draws the object./*  ww  w  .ja v  a 2s .c om*/
 *
 * @param graphics
 *          the graphics device.
 * @param area
 *          the area inside which the object should be drawn.
 */
public void draw(final Graphics2D graphics, final Rectangle2D area) {
    final Graphics2D g2 = (Graphics2D) graphics.create();
    if (isDrawPageBackground()) {
        g2.setPaint(Color.white);
        g2.fill(area);
    }
    g2.translate(-area.getX(), -area.getY());

    try {
        final StrictBounds pageBounds = StrictGeomUtility.createBounds(area.getX(), area.getY(),
                area.getWidth(), area.getHeight());
        this.pageArea = pageBounds;
        this.drawArea = pageBounds;
        this.graphics = g2;

        if (startBlockBox(rootBox)) {
            processRootBand(pageBounds);
        }
        finishBlockBox(rootBox);
    } finally {
        this.graphics = null;
        this.drawArea = null;
        g2.dispose();
    }
}

From source file:org.apache.fop.render.pcl.PCLRenderer.java

/**
 * {@inheritDoc}/*from ww w .j a  v  a 2  s . c o m*/
 */
protected void renderText(final TextArea text) {
    renderInlineAreaBackAndBorders(text);

    String fontname = getInternalFontNameForArea(text);
    final int fontsize = text.getTraitAsInteger(Trait.FONT_SIZE);

    //Determine position
    int saveIP = currentIPPosition;
    final int rx = currentIPPosition + text.getBorderAndPaddingWidthStart();
    int bl = currentBPPosition + text.getOffset() + text.getBaselineOffset();

    try {

        final Color col = (Color) text.getTrait(Trait.COLOR);
        boolean pclFont = pclUtil.isAllTextAsBitmaps() ? false
                : HardcodedFonts.setFont(gen, fontname, fontsize, text.getText());
        if (pclFont) {
            //this.currentFill = col;
            if (col != null) {
                //useColor(ct);
                gen.setTransparencyMode(true, false);
                gen.selectGrayscale(col);
            }

            saveGraphicsState();
            graphicContext.translate(rx, bl);
            setCursorPos(0, 0);
            gen.setTransparencyMode(true, true);
            if (text.hasUnderline()) {
                gen.writeCommand("&d0D");
            }
            super.renderText(text); //Updates IPD and renders words and spaces
            if (text.hasUnderline()) {
                gen.writeCommand("&d@");
            }
            restoreGraphicsState();
        } else {
            //Use Java2D to paint different fonts via bitmap
            final Font font = getFontFromArea(text);
            final int baseline = text.getBaselineOffset();

            //for cursive fonts, so the text isn't clipped
            int extraWidth = font.getFontSize() / 3;
            final FontMetricsMapper mapper = (FontMetricsMapper) fontInfo.getMetricsFor(font.getFontName());
            int maxAscent = mapper.getMaxAscent(font.getFontSize()) / 1000;
            final int additionalBPD = maxAscent - baseline;

            Graphics2DAdapter g2a = getGraphics2DAdapter();
            final Rectangle paintRect = new Rectangle(rx, currentBPPosition + text.getOffset() - additionalBPD,
                    text.getIPD() + extraWidth, text.getBPD() + additionalBPD);
            RendererContext rc = createRendererContext(paintRect.x, paintRect.y, paintRect.width,
                    paintRect.height, null);
            Map atts = new java.util.HashMap();
            atts.put(ImageHandlerUtil.CONVERSION_MODE, ImageHandlerUtil.CONVERSION_MODE_BITMAP);
            atts.put(SRC_TRANSPARENCY, "true");
            rc.setProperty(RendererContextConstants.FOREIGN_ATTRIBUTES, atts);

            Graphics2DImagePainter painter = new Graphics2DImagePainter() {

                public void paint(Graphics2D g2d, Rectangle2D area) {
                    g2d.setFont(mapper.getFont(font.getFontSize()));
                    g2d.translate(0, baseline + additionalBPD);
                    g2d.scale(1000, 1000);
                    g2d.setColor(col);
                    Java2DRenderer.renderText(text, g2d, font);
                    renderTextDecoration(g2d, mapper, fontsize, text, 0, 0);
                }

                public Dimension getImageSize() {
                    return paintRect.getSize();
                }

            };
            g2a.paintImage(painter, rc, paintRect.x, paintRect.y, paintRect.width, paintRect.height);
            currentIPPosition = saveIP + text.getAllocIPD();
        }

    } catch (IOException ioe) {
        handleIOTrouble(ioe);
    }
}

From source file:org.rdv.viz.image.ImageViz.java

/**
 * Print the displayed image. If no image is being displayed, this will method
 * will do nothing.//  w ww. j  a  v  a 2s .c  om
 */
private void printImage() {
    // get the displayed image
    final Image displayedImage = getDisplayedImage();
    if (displayedImage == null) {
        return;
    }

    // setup a print job
    PrinterJob printJob = PrinterJob.getPrinterJob();

    // set the renderer for the image
    printJob.setPrintable(new Printable() {
        public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
            //we only have one page to print
            if (pageIndex != 0) {
                return Printable.NO_SUCH_PAGE;
            }

            Graphics2D g2d = (Graphics2D) g;

            // move to corner of imageable page
            g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

            // get page dimensions
            double pageWidth = pageFormat.getImageableWidth();
            double pageHeight = pageFormat.getImageableHeight();

            // get image dimensions
            int imageWidth = displayedImage.getWidth(null);
            int imageHeight = displayedImage.getHeight(null);

            // get scale factor for image
            double widthScale = pageWidth / imageWidth;
            double heightScale = pageHeight / imageHeight;
            double scale = Math.min(widthScale, heightScale);

            // draw image with width and height scaled to page
            int scaledWidth = (int) (scale * imageWidth);
            int scaledHeight = (int) (scale * imageHeight);
            g2d.drawImage(displayedImage, 0, 0, scaledWidth, scaledHeight, null);

            return Printable.PAGE_EXISTS;
        }

    });

    // set the job name to the channel name (plus jpg extension)
    // this is used as a hint for a file name when printing to file
    String channelName = (String) channels.iterator().next();
    String jobName = channelName.replace("/", " - ");
    if (!jobName.endsWith(".jpg")) {
        jobName += ".jpg";
    }
    printJob.setJobName(jobName);

    // show the print dialog and print if ok clicked
    if (printJob.printDialog()) {
        try {
            printJob.print();
        } catch (PrinterException pe) {
            JOptionPane.showMessageDialog(null, "Failed to print image.", "Print Image Error",
                    JOptionPane.ERROR_MESSAGE);
            pe.printStackTrace();
        }
    }
}

From source file:edu.ku.brc.ui.UIRegistry.java

/**
 * Writes a string message into the BufferedImage on GlassPane and sets the main component's visibility to false and
 * shows the GlassPane./* w  ww.jav  a2 s  . co m*/
 * @param msg the message
 * @param pointSize the Font point size for the message to be writen in
 */
public static GhostGlassPane writeGlassPaneMsg(final String msg, final int pointSize) {
    GhostGlassPane glassPane = getGlassPane();
    if (glassPane != null) {
        glassPane.finishDnD();
    }

    glassPane.setMaskingEvents(true);

    Component mainComp = get(MAINPANE);
    if (mainComp != null && glassPane != null) {
        JFrame frame = (JFrame) get(FRAME);
        frameRect = frame.getBounds();

        int y = 0;
        JMenuBar menuBar = null;
        Dimension size = mainComp.getSize();
        if (UIHelper.getOSType() != UIHelper.OSTYPE.MacOSX) {
            menuBar = frame.getJMenuBar();
            size.height += menuBar.getSize().height;
            y += menuBar.getSize().height;
        }
        BufferedImage buffer = getGlassPaneBufferedImage(size.width, size.height);
        Graphics2D g2 = buffer.createGraphics();
        if (menuBar != null) {
            menuBar.paint(g2);
        }
        g2.translate(0, y);
        mainComp.paint(g2);
        g2.translate(0, -y);

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(new Color(255, 255, 255, 128));
        g2.fillRect(0, 0, size.width, size.height);

        g2.setFont(new Font((new JLabel()).getFont().getName(), Font.BOLD, pointSize));
        FontMetrics fm = g2.getFontMetrics();

        int tw = fm.stringWidth(msg);
        int th = fm.getHeight();
        int tx = (size.width - tw) / 2;
        int ty = (size.height - th) / 2;

        int expand = 20;
        int arc = expand * 2;
        g2.setColor(Color.WHITE);
        g2.fillRoundRect(tx - (expand / 2), ty - fm.getAscent() - (expand / 2), tw + expand, th + expand, arc,
                arc);

        g2.setColor(Color.DARK_GRAY);
        g2.drawRoundRect(tx - (expand / 2), ty - fm.getAscent() - (expand / 2), tw + expand, th + expand, arc,
                arc);

        g2.setColor(Color.BLACK);
        g2.drawString(msg, tx, ty);
        g2.dispose();

        glassPane.setImage(buffer);
        glassPane.setPoint(new Point(0, 0), GhostGlassPane.ImagePaintMode.ABSOLUTE);
        glassPane.setOffset(new Point(0, 0));

        glassPane.setVisible(true);
        mainComp.setVisible(false);

        //Using paintImmediately fixes problems with glass pane not showing, such as for workbench saves initialed
        //during workbench or app shutdown. Don't know if there is a better way to fix it.
        //glassPane.repaint();
        glassPane.paintImmediately(glassPane.getBounds());
        showingGlassPane = true;
    }

    return glassPane;
}