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:de.fhg.igd.mapviewer.waypoints.CustomWaypointPainter.java

private void processWaypoint(W w, int minX, int minY, int width, int height, PixelConverter converter, int zoom,
        Graphics2D g) {
    try {//from   www . j av a2 s. c  o  m
        Point2D point = converter.geoToPixel(w.getPosition(), zoom);
        int x = (int) (point.getX() - minX);
        int y = (int) (point.getY() - minY);
        PixelConverter converterWrapper = new TranslationPixelConverterDecorator(converter, (int) point.getX(),
                (int) point.getY());
        g.translate(x, y);
        Rectangle gBounds = new Rectangle(minX - (int) point.getX(), minY - (int) point.getY(), width, height);
        renderer.paintWaypoint(g, converterWrapper, zoom, w, gBounds);
        g.translate(-x, -y);
    } catch (IllegalGeoPositionException e) {
        // waypoint not in map bounds or position invalid
        // log.warn("Error painting waypoint", e);
    }
}

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

public void paintNode(Graphics2D g, GraphicNode node) {
    Rectangle bounds = getBounds(node);
    if (isEditing(node)) {
        editor.paintEditor(node);//from  ww  w  .  j a  v a2  s  .  c  om
    } else {
        JComponent c = renderer.getRendererComponent(node, ((NetworkParams) graphInfo).getZoom());
        if (container == null) {
            //c=new JLabel("test");
            c.setDoubleBuffered(false);
            c.setOpaque(false);
            c.setForeground(Color.BLACK);
            c.setSize(bounds.width, bounds.height);
            g.translate(bounds.x, bounds.y);
            c.doLayout();
            c.print(g);
            g.translate(-bounds.x, -bounds.y);
        } else
            rendererPane.paintComponent(g, c, container, bounds.x, bounds.y, bounds.width, bounds.height, true);
    }
}

From source file:ScribbleDragAndDrop.java

/**
 * This method implements the DragGestureListener interface. It will be
 * invoked when the DragGestureRecognizer thinks that the user has initiated
 * a drag. If we're not in drawing mode, then this method will try to figure
 * out which Scribble object is being dragged, and will initiate a drag on
 * that object./* ww  w . j av a2  s . c o m*/
 */
public void dragGestureRecognized(DragGestureEvent e) {
    // Don't drag if we're not in drag mode
    if (!dragMode)
        return;

    // Figure out where the drag started
    MouseEvent inputEvent = (MouseEvent) e.getTriggerEvent();
    int x = inputEvent.getX();
    int y = inputEvent.getY();

    // Figure out which scribble was clicked on, if any by creating a
    // small rectangle around the point and testing for intersection.
    Rectangle r = new Rectangle(x - LINEWIDTH, y - LINEWIDTH, LINEWIDTH * 2, LINEWIDTH * 2);
    int numScribbles = scribbles.size();
    for (int i = 0; i < numScribbles; i++) { // Loop through the scribbles
        Scribble s = (Scribble) scribbles.get(i);
        if (s.intersects(r)) {
            // The user started the drag on top of this scribble, so
            // start to drag it.

            // First, remember which scribble is being dragged, so we can
            // delete it later (if this is a move rather than a copy)
            beingDragged = s;

            // Next, create a copy that will be the one dragged
            Scribble dragScribble = (Scribble) s.clone();
            // Adjust the origin to the point the user clicked on.
            dragScribble.translate(-x, -y);

            // Choose a cursor based on the type of drag the user initiated
            Cursor cursor;
            switch (e.getDragAction()) {
            case DnDConstants.ACTION_COPY:
                cursor = DragSource.DefaultCopyDrop;
                break;
            case DnDConstants.ACTION_MOVE:
                cursor = DragSource.DefaultMoveDrop;
                break;
            default:
                return; // We only support move and copys
            }

            // Some systems allow us to drag an image along with the
            // cursor. If so, create an image of the scribble to drag
            if (dragSource.isDragImageSupported()) {
                Rectangle scribbleBox = dragScribble.getBounds();
                Image dragImage = this.createImage(scribbleBox.width, scribbleBox.height);
                Graphics2D g = (Graphics2D) dragImage.getGraphics();
                g.setColor(new Color(0, 0, 0, 0)); // transparent background
                g.fillRect(0, 0, scribbleBox.width, scribbleBox.height);
                g.setColor(Color.black);
                g.setStroke(linestyle);
                g.translate(-scribbleBox.x, -scribbleBox.y);
                g.draw(dragScribble);
                Point hotspot = new Point(-scribbleBox.x, -scribbleBox.y);

                // Now start dragging, using the image.
                e.startDrag(cursor, dragImage, hotspot, dragScribble, this);
            } else {
                // Or start the drag without an image
                e.startDrag(cursor, dragScribble, this);
            }
            // After we've started dragging one scribble, stop looking
            return;
        }
    }
}

From source file:com.alvermont.terraj.util.io.PrintUtilities.java

/**
 * Print the component into a graphics context
 * /*  w  ww. ja va  2s .  c  o  m*/
 * @param g The <code>Graphics</code> object to be used for printing.
 * This should be a <code>Graphics2D</code> instance
 * @param pf The page format to be used
 * @param pageIndex The number of the page being printed
 * @return An indication of whether the page existed. Silly people using
 * magic numbers. Oh well.
 */
public int print(Graphics g, PageFormat pf, int pageIndex) {
    int response = NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D) g;
    // for faster printing, turn off double buffering
    disableDoubleBuffering(componentToBePrinted);

    Dimension d = componentToBePrinted.getSize(); //get size of document
    double panelWidth = d.width; //width in pixels
    double panelHeight = d.height; //height in pixels
    double pageHeight = pf.getImageableHeight(); //height of printer page
    double pageWidth = pf.getImageableWidth(); //width of printer page
    double scale = pageWidth / panelWidth;

    int totalNumPages = (int) Math.ceil(scale * panelHeight / pageHeight);
    // make sure not print empty pages
    if (pageIndex >= totalNumPages) {
        response = NO_SUCH_PAGE;
    } else {
        // shift Graphic to line up with beginning of print-imageable region
        g2.translate(pf.getImageableX(), pf.getImageableY());
        // shift Graphic to line up with beginning of next page to print
        g2.translate(0f, -pageIndex * pageHeight);
        // scale the page so the width fits...
        g2.scale(scale, scale);
        componentToBePrinted.paint(g2); //repaint the page for printing
        enableDoubleBuffering(componentToBePrinted);
        response = Printable.PAGE_EXISTS;
    }

    return response;
}

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

/**
 * Print the displayed image. If no image is being displayed, this will method
 * will do nothing.//from  w w w. j  a v a2  s . co  m
 */
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) seriesList_.getChannels().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:BookTest.java

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    PageFormat pageFormat = book.getPageFormat(currentPage);

    double xoff; // x offset of page start in window
    double yoff; // y offset of page start in window
    double scale; // scale factor to fit page in window
    double px = pageFormat.getWidth();
    double py = pageFormat.getHeight();
    double sx = getWidth() - 1;
    double sy = getHeight() - 1;
    if (px / py < sx / sy) // center horizontally
    {/*from  w  w  w.ja  v a2s.co  m*/
        scale = sy / py;
        xoff = 0.5 * (sx - scale * px);
        yoff = 0;
    } else
    // center vertically
    {
        scale = sx / px;
        xoff = 0;
        yoff = 0.5 * (sy - scale * py);
    }
    g2.translate((float) xoff, (float) yoff);
    g2.scale((float) scale, (float) scale);

    // draw page outline (ignoring margins)
    Rectangle2D page = new Rectangle2D.Double(0, 0, px, py);
    g2.setPaint(Color.white);
    g2.fill(page);
    g2.setPaint(Color.black);
    g2.draw(page);

    Printable printable = book.getPrintable(currentPage);
    try {
        printable.print(g2, pageFormat, currentPage);
    } catch (PrinterException e) {
        g2.draw(new Line2D.Double(0, 0, px, py));
        g2.draw(new Line2D.Double(px, 0, 0, py));
    }
}

From source file:me.solhub.simple.engine.DebugLocationsStructure.java

@Override
protected void draw() {
    Graphics2D g = (Graphics2D) getGraphics();
    Graphics2D bbg = (Graphics2D) _backBuffer.getGraphics();

    //anti-aliasing code
    //        bbg.setRenderingHint(
    //                RenderingHints.KEY_TEXT_ANTIALIASING,
    //                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    //        bbg.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );

    bbg.setColor(Color.WHITE);/*w ww .  j ava 2s .co  m*/
    bbg.fillRect(0, 0, _windowWidth, _windowHeight);

    bbg.translate(_xOffset, _yOffset);

    // draw destinations
    bbg.setColor(_simState.startingDestination.getColor());
    bbg.drawOval(-(int) _simState.startingDestination.getRadius(),
            -(int) _simState.startingDestination.getRadius(),
            (int) _simState.startingDestination.getRadius() * 2,
            (int) _simState.startingDestination.getRadius() * 2);
    Iterator<Entry<Vector2D, Color>> blah = _destinationColors.entrySet().iterator();
    double destinationRadius = _simState.getDestinationRadius();
    while (blah.hasNext()) {
        Entry<Vector2D, Color> temp = blah.next();
        bbg.setColor(temp.getValue());
        //calculate center coordinate
        int x = (int) (temp.getKey().getX() - (destinationRadius));
        int y = (int) (temp.getKey().getY() - (destinationRadius));
        //drawOval draws a circle inside a rectangle
        bbg.drawOval(x, y, _simState.getDestinationRadius() * 2, _simState.getDestinationRadius() * 2);
    }

    // draw each of the agents
    Iterator<Agent> agentIter = _simState.getAgentIterator();
    while (agentIter.hasNext()) {
        Agent temp = agentIter.next();
        if (temp.isAlive()) {
            // decide whether to color for destination or group
            //                if( isDestinationColors )
            //                {
            //                    // if stopped then blink white and destination color
            //                    if( temp.hasReachedDestination() )
            //                    {
            //                        if( pulseWhite % 20 == 0 )
            //                        {
            //                            bbg.setColor( Color.WHITE );
            //                        }
            //                        else
            //                        {
            //                            bbg.setColor( temp.getDestinationColor() );
            //                        }
            //                    }
            //                    else
            //                    {
            //                        bbg.setColor( temp.getDestinationColor() );
            //                    }
            //                }
            //                else
            //                {
            //                    // if stopped then blink black and white
            //                    if( temp.hasReachedDestination() )
            //                    {
            //                        if( pulseWhite % 20 == 0 )
            //                        {
            //                            bbg.setColor( Color.WHITE );
            //                        }
            //                        else
            //                        {
            //                            bbg.setColor( temp.getGroup().getGroupColor() );
            //                        }
            //                    }
            //                    //set color to red if cancelled and global and not multiple initiators
            //                    else if(temp.getCurrentDecision().getDecision().getDecisionType().equals(
            //                            DecisionType.CANCELLATION ) 
            //                            && _simState.getCommunicationType().equals( "global" )
            //                            && !Agent.canMultipleInitiate()
            //                            )
            //                    {
            //                        bbg.setColor( Color.RED );
            //                    }
            //                    else
            //                    {
            //                        bbg.setColor( temp.getGroup().getGroupColor() );
            //                    }
            //                }

            double dx = temp.getCurrentDestination().getX() - temp.getCurrentLocation().getX();
            double dy = temp.getCurrentDestination().getY() - temp.getCurrentLocation().getY();
            double heading = Math.atan2(dy, dx);
            Utils.drawDirectionalTriangle(bbg, heading - Math.PI / 2, temp.getCurrentLocation().getX(),
                    temp.getCurrentLocation().getY(), 7, temp.getPreferredDestination().getColor(),
                    temp.getGroup().getGroupColor());

            //                bbg.fillOval( (int) temp.getCurrentLocation().getX() - _agentSize,
            //                        (int) temp.getCurrentLocation().getY() - _agentSize , _agentSize * 2, _agentSize * 2 );
        }
    }
    pulseWhite++;
    bbg.setColor(Color.BLACK);
    // the total number of groups
    bbg.setFont(_infoFont);

    bbg.drawString("Run: " + (_simState.getCurrentSimulationRun() + 1), _fontXOffset, _fontYOffset);
    bbg.drawString("Time: " + _simState.getSimulationTime(), _fontXOffset, _fontYOffset + _fontSize);
    bbg.drawString("Delay: " + LIVE_DELAY, _fontXOffset, _fontYOffset + _fontSize * 2);

    if (_simState.getCommunicationType().equals("global") && !Agent.canMultipleInitiate()) {
        String initiatorName = "None";
        if (_initiatingAgent != null) {
            initiatorName = _initiatingAgent.getId().toString();
        }
        bbg.drawString("Init: " + initiatorName, _fontXOffset, _fontYOffset + _fontSize * 3);
        bbg.drawString("Followers: " + _numberFollowing, _fontXOffset, _fontYOffset + _fontSize * 4);
    } else {
        bbg.drawString("Groups: " + _simState.getNumberGroups(), _fontXOffset, _fontYOffset + _fontSize * 3);
        bbg.drawString("Reached: " + _simState.numReachedDestination, _fontXOffset,
                _fontYOffset + _fontSize * 4);
        bbg.drawString("Inits: " + _simState.numInitiating, _fontXOffset, _fontYOffset + _fontSize * 5);
        bbg.drawString("Eaten: " + _simState.getPredator().getTotalAgentsEaten(), _fontXOffset,
                _fontYOffset + _fontSize * 6);
    }

    g.scale(_zoom, _zoom);
    g.drawImage(_backBuffer, 0, 0, this);
    if (SHOULD_VIDEO) {

        // setup to save to a png
        BufferedImage buff = new BufferedImage(_windowWidth, _windowHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D temp = (Graphics2D) buff.getGraphics();
        temp.scale(8, 4);
        temp.drawImage(_backBuffer, 0, 0, this);
        // sub-directory
        File dir = new File("video");
        dir.mkdir();
        // format string for filename
        String filename = String.format("video/run-%03d-time-%05d.png", _simState.getCurrentSimulationRun(),
                _simState.getSimulationTime());
        File outputfile = new File(filename);
        // save it
        try {
            ImageIO.write(buff, "png", outputfile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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

private IFPainter createAllBitmapPainter() {
    double scale = gen.getMaximumBitmapResolution() / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION;
    Rectangle printArea = this.currentPageDefinition.getLogicalPageRect();
    int bitmapWidth = (int) Math.ceil(UnitConv.mpt2px(printArea.width, gen.getMaximumBitmapResolution()));
    int bitmapHeight = (int) Math.ceil(UnitConv.mpt2px(printArea.height, gen.getMaximumBitmapResolution()));
    this.currentImage = createBufferedImage(bitmapWidth, bitmapHeight);
    Graphics2D graphics2D = this.currentImage.createGraphics();

    if (!PCLGenerator.isJAIAvailable()) {
        RenderingHints hints = new RenderingHints(null);
        //These hints don't seem to make a difference :-( Not seeing any dithering on Sun Java.
        hints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        graphics2D.addRenderingHints(hints);
    }/*from w  w w  .j a  v a2 s. c om*/

    //Ensure white page background
    graphics2D.setBackground(Color.WHITE);
    graphics2D.clearRect(0, 0, bitmapWidth, bitmapHeight);

    graphics2D.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
            RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
    graphics2D.scale(scale / 1000f, scale / 1000f);
    graphics2D.translate(-printArea.x, -printArea.y);

    return new Java2DPainter(graphics2D, getContext(), getFontInfo());
}

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

public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
    if (pageIndex > 0) {
        return NO_SUCH_PAGE;
    } else {/*  w  w w . j  a va  2s.c  om*/
        Graphics2D g2d = (Graphics2D) g;
        g2d.setBackground(Color.white);
        g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

        Dimension td = this.getPreferredSize();
        double sx = pageFormat.getImageableWidth() / td.width;
        double sy = pageFormat.getImageableHeight() / td.height;
        double s = Math.min(sx, sy);
        if (s < 1.)
            g2d.scale(s, s);

        RepaintManager.currentManager(this).setDoubleBufferingEnabled(false);
        this.paint(g2d);
        RepaintManager.currentManager(this).setDoubleBufferingEnabled(true);

        return PAGE_EXISTS;
    }
}

From source file:ucar.unidata.idv.flythrough.ChartDecorator.java

/**
 * _more_/*from   ww  w.  j  a va  2s  .c o m*/
 *
 * @param g2 _more_
 * @param comp _more_
 *
 * @return _more_
 */
public boolean paintDashboard(Graphics2D g2, JComponent comp) {
    try {
        List<SampleInfo> infos = new ArrayList<SampleInfo>(sampleInfos);
        if (infos.size() == 0) {
            return false;
        }
        Rectangle b = comp.getBounds();
        JFrame dummyFrame = new JFrame("");
        XYSeriesCollection dataset = new XYSeriesCollection();
        JFreeChart chart = Flythrough.createChart(dataset);
        XYPlot xyPlot = (XYPlot) chart.getPlot();

        int chartHeight = b.height - flythrough.getDashboardImage().getHeight(null);
        chartHeight = Math.max(chartHeight, 50);
        int chartWidth = Math.min(chartHeight * 4, b.width);

        int dx = b.width / 2 - chartWidth / 2;
        int dy = 0;

        Image lastImage = lastChartImage;
        if ((lastImage != null) && (lastImage.getWidth(null) == chartWidth)
                && (lastImage.getHeight(null) == chartHeight)) {
            g2.translate(dx, dy);
            g2.drawImage(lastImage, 0, 0, null);
            g2.translate(-dx, -dy);
            return false;
        }

        for (int i = 0; i < infos.size(); i++) {
            SampleInfo info = infos.get(i);
            ValueAxis rangeAxis = new NumberAxis(info.getName());
            if (info.getRange() != null) {
                rangeAxis
                        .setRange(new org.jfree.data.Range(info.getRange().getMin(), info.getRange().getMax()));
            }
            dataset = new XYSeriesCollection();
            dataset.addSeries(info.getSeries());
            xyPlot.setRangeAxis(i, rangeAxis, false);
            xyPlot.setDataset(i, dataset);
            xyPlot.mapDatasetToRangeAxis(i, i);
            final Color color = COLORS[i % COLORS.length];
            XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false) {
                public Paint xgetItemPaint(final int row, final int column) {
                    return color;
                }
            };
            renderer.setSeriesPaint(0, color);
            xyPlot.setRenderer(i, renderer);
        }

        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(chartWidth, chartHeight));
        dummyFrame.setContentPane(chartPanel);
        dummyFrame.pack();
        Image image = ImageUtils.getImage(chartPanel);
        lastChartImage = image;
        g2.translate(dx, dy);
        g2.drawImage(image, 0, 0, null);
        g2.translate(-dx, -dy);
    } catch (Exception exc) {
        logException("Painting chart", exc);

    }

    return false;

}