Example usage for java.awt Graphics2D setColor

List of usage examples for java.awt Graphics2D setColor

Introduction

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

Prototype

public abstract void setColor(Color c);

Source Link

Document

Sets this graphics context's current color to the specified color.

Usage

From source file:rod_design_compute.ShowPanel.java

private void paintSR(SR rodSR, Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setStroke(new BasicStroke(2f));

    if (rodSR.flag == true) {
        g2d.setColor(Color.red);
        g.drawLine(toScreenX(rodSR.getPointA().X), toScreenY(rodSR.getPointA().Y),
                toScreenX(rodSR.getPointE().X), toScreenY(rodSR.getPointE().Y));
        g.drawLine(toScreenX(rodSR.getPointB().X), toScreenY(rodSR.getPointB().Y),
                toScreenX(rodSR.getPointE().X), toScreenY(rodSR.getPointE().Y));
        drawOtherPoint(rodSR.getPointE(), g);
        g2d.setColor(Color.black);
    }//from   w w  w . j  a v  a2s  .co m

    g2d.setColor(Color.green);
    g.drawLine(toScreenX(rodSR.getPointA().X), toScreenY(rodSR.getPointA().Y), toScreenX(rodSR.getPointB().X),
            toScreenY(rodSR.getPointB().Y));
    g2d.setColor(Color.black);

    drawBasePoint(rodSR.getPointA(), g);
    drawJunctionPoint(rodSR.getPointB(), g);
}

From source file:jhplot.HPlotChart.java

public void drawToGraphics2D(Graphics2D g, int width, int height) {
    // self.chartCoordsMap = {} #Maps a chart to its raw screen coords, used
    // for converting coords
    g.setColor(Color.white);
    g.fillRect(0, 0, width, height);// w ww. j av a2  s  .  c o m
    //
    // int boxWidth = width / this.chartarray[0].length;
    // int boxHeight = height / this.chartarray.length;

    int cols = 1;
    int rows = 1;
    int boxWidth = width / cols;
    int boxHeight = height / rows;

    //
    // # print "boxWidth ", boxWidth
    // # print "boxHeight ", boxHeight

    // for (int row = 0; row < chartarray.length; row++)
    int currentChartIndex = 0;

    for (int i2 = 0; i2 < rows; i2++) {
        for (int i1 = 0; i1 < cols; i1++) {

            currentChartIndex++;
            if (chart != null) {

                int rowsUsed = 1;
                int colsUsed = 1;
                int chartX = boxWidth * i1;
                int chartY = boxHeight * i2;
                int chartwidth = boxWidth;
                int chartheight = boxHeight;
                // #Get Horizontalspace
                // for (int c = col; c > -1; c--)
                // {
                // // for c in range(col, -1, -1):
                // // if self.chartArray[row][c] == None:
                // if(this.chartarray[row][c] == null)
                // rowsUsed++;
                //
                // // rowsUsed = rowsUsed + 1
                // // #print "adding row"
                // }
                chartwidth = boxWidth * rowsUsed;
                chartheight = boxHeight;
                chartX = chartX - (rowsUsed - 1) * boxWidth;
                //
                // # chart.configureDomainAxes()
                // # chart.configureRangeAxes()
                //
                // #Testing axes ranges not updated
                // from org.jfree.chart.event import PlotChangeEvent
                // chart[i1][i2].plotChanged(new
                // PlotChangeEvent(chart[i1][i2].getXYPlot()));
                chart.plotChanged(new PlotChangeEvent(chart.getPlot()));
                //
                ChartRenderingInfo info = new ChartRenderingInfo();
                //
                chart.draw(g, new java.awt.Rectangle(chartX, chartY, chartwidth, chartheight),
                        new Point(chartX, chartY), info);
                // self.chartToInfoMap[chart] = info
                //
                // self.chartCoordsMap[chart] = [chartX ,chartY,chartwidth,
                // chartheight]

            }
        }
    }

}

From source file:ucar.unidata.idv.control.chart.RangeFilter.java

/**
 * Draws the annotation./* www . j a v a2s. c  om*/
 *
 * @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  an optional info object that will be populated with
 *              entity information.
 */
public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis,
        int rendererIndex, PlotRenderingInfo info) {
    super.setGraphicsState(g2);
    if (!getPlotWrapper().okToDraw(this)) {
        return;
    }
    g2.setStroke(new BasicStroke());
    boolean selected = getSelected();
    if (attached != null) {
        selected |= attached.getSelected();
    }

    if (selected) {
        g2.setColor(COLOR_SELECTED);
    } else {
        g2.setColor(getColor());
    }
    y = (int) rangeAxis.valueToJava2D(rangeValue, dataArea, RectangleEdge.LEFT);

    int width = (int) ANNOTATION_WIDTH;
    int width2 = (int) (ANNOTATION_WIDTH / 2);
    x = (int) dataArea.getX();
    //        System.err.println("x/y:" + x +"/" +y);

    int[] xs;
    int[] ys;
    if (type == TYPE_LESSTHAN) {
        xs = new int[] { x, x + width, x + width2, x };
        ys = new int[] { y, y, y + width, y };
    } else {
        xs = new int[] { x, x + width, x + width2, x };
        ys = new int[] { y, y, y - width, y };

    }
    g2.fillPolygon(xs, ys, xs.length);

    g2.setColor(Color.gray);
    g2.drawLine(x + width, y, (int) (dataArea.getX() + dataArea.getWidth()), y);

    if ((attached != null) && (type == TYPE_LESSTHAN)) {
        int otherY = (int) rangeAxis.valueToJava2D(attached.rangeValue, dataArea, RectangleEdge.LEFT);

        g2.drawLine(x + width2, y + width, x + width2, otherY - width);
    }
}

From source file:main.MapKit.java

@Override
public void paintWaypoint(Graphics2D g, JXMapViewer viewer, MyWaypoint w) {
    g = (Graphics2D) g.create();//ww  w  .j  a  va 2 s . co m

    Point2D point = viewer.getTileFactory().geoToPixel(w.getPosition(), viewer.getZoom());
    int x = (int) point.getX();
    int y = (int) point.getY();

    if (w.amount == -1) { //means it's an original data point
        int fontSize = 28 - viewer.getZoom() * 2; //font size is larger when zoom in
        if (fontSize < 6)
            fontSize = 6;
        g.setFont(new Font("Arial", Font.PLAIN, fontSize));
        g.setColor(w.color);
        g.drawString("x", x - fontSize / 2, y + fontSize / 2);
        g.dispose();
        return;
    }

    if (origImage == null) {
        return;
    }

    BufferedImage myImg = map.get(w.color);

    if (myImg == null) {
        myImg = convert(origImage, w.color);
        map.put(w.color, myImg);
    }

    g.drawImage(myImg, x - myImg.getWidth() / 2, y - myImg.getHeight(), null);

    String label = String.valueOf(w.amount);

    //      g.setFont(font);
    FontMetrics metrics = g.getFontMetrics();
    int tw = metrics.stringWidth(label);
    int th = 1 + metrics.getAscent();

    //      g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.drawString(label, x - tw / 2, y + th);

    g.dispose();
}

From source file:fr.fg.server.core.TerritoryManager.java

private static BufferedImage createTerritoryMap(int idSector) {
    List<Area> areas = new ArrayList<Area>(DataAccess.getAreasBySector(idSector));

    float[][] points = new float[areas.size()][2];
    int[] dominatingAllies = new int[areas.size()];
    int i = 0;/*from   w  w w .  j a v a2s.co m*/
    for (Area area : areas) {
        points[i][0] = area.getX() * MAP_SCALE;
        points[i][1] = area.getY() * MAP_SCALE;
        dominatingAllies[i] = area.getIdDominatingAlly();
        i++;
    }

    Hull hull = new Hull(points);
    MPolygon hullPolygon = hull.getRegion();
    float[][] newPoints = new float[points.length + hullPolygon.count()][2];
    System.arraycopy(points, 0, newPoints, 0, points.length);

    float[][] hullCoords = hullPolygon.getCoords();

    for (i = 0; i < hullPolygon.count(); i++) {
        double angle = Math.atan2(hullCoords[i][1], hullCoords[i][0]);
        double length = Math.sqrt(hullCoords[i][0] * hullCoords[i][0] + hullCoords[i][1] * hullCoords[i][1]);

        newPoints[i + points.length][0] = (float) (Math.cos(angle) * (length + 8 * MAP_SCALE));
        newPoints[i + points.length][1] = (float) (Math.sin(angle) * (length + 8 * MAP_SCALE));
    }

    points = newPoints;

    Voronoi voronoi = new Voronoi(points);
    Delaunay delaunay = new Delaunay(points);

    // Dcoupage en rgions
    MPolygon[] regions = voronoi.getRegions();

    // Calcule le rayon de la galaxie
    int radius = 0;

    for (Area area : areas) {
        radius = Math.max(radius, area.getX() * area.getX() + area.getY() * area.getY());
    }

    radius = (int) Math.floor(Math.sqrt(radius) * MAP_SCALE) + 10 * MAP_SCALE;
    int diameter = 2 * radius + 1;

    // Construit l'image avec les quadrants
    BufferedImage territoriesImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g = (Graphics2D) territoriesImage.getGraphics();

    // Affecte une couleur  chaque alliance
    HashMap<Integer, Color> alliesColors = new HashMap<Integer, Color>();

    for (Area area : areas) {
        int idDominatingAlly = area.getIdDominatingAlly();
        if (idDominatingAlly != 0)
            alliesColors.put(idDominatingAlly,
                    Ally.TERRITORY_COLORS[DataAccess.getAllyById(idDominatingAlly).getColor()]);
    }

    Polygon[] polygons = new Polygon[regions.length];
    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] != 0) {
            polygons[i] = createPolygon(regions[i].getCoords(), radius + 1, 3);
        }
    }

    // Dessine tous les secteurs
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0)
            continue;

        Polygon p = polygons[i];

        // Dessine le polygone
        g.setColor(alliesColors.get(dominatingAllies[i]));
        g.fill(p);

        // Rempli les espaces entre les polygones adjacents qui
        // correspondent au territoire d'une mme alliance
        int[] linkedRegions = delaunay.getLinked(i);
        for (int j = 0; j < linkedRegions.length; j++) {
            int linkedRegion = linkedRegions[j];

            if (linkedRegion >= areas.size())
                continue;

            if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                if (linkedRegion <= i)
                    continue;

                float[][] coords1 = regions[i].getCoords();
                float[][] coords2 = regions[linkedRegion].getCoords();

                int junctionIndex = 0;
                int[][] junctions = new int[2][2];

                search: for (int k = 0; k < coords1.length; k++) {
                    for (int l = 0; l < coords2.length; l++) {
                        if (coords1[k][0] == coords2[l][0] && coords1[k][1] == coords2[l][1]) {
                            junctions[junctionIndex][0] = k;
                            junctions[junctionIndex][1] = l;

                            junctionIndex++;

                            if (junctionIndex == 2) {
                                int[] xpts = new int[] { polygons[i].xpoints[junctions[0][0]],
                                        polygons[linkedRegion].xpoints[junctions[0][1]],
                                        polygons[linkedRegion].xpoints[junctions[1][1]],
                                        polygons[i].xpoints[junctions[1][0]], };
                                int[] ypts = new int[] { polygons[i].ypoints[junctions[0][0]],
                                        polygons[linkedRegion].ypoints[junctions[0][1]],
                                        polygons[linkedRegion].ypoints[junctions[1][1]],
                                        polygons[i].ypoints[junctions[1][0]], };

                                Polygon border = new Polygon(xpts, ypts, 4);
                                g.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
                                g.fill(border);
                                g.draw(border);
                                break search;
                            }
                            break;
                        }
                    }
                }
            }
        }
    }

    // Dessine des lignes de contours des territoires
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0)
            continue;

        g.setStroke(new BasicStroke(1.5f));
        g.setColor(alliesColors.get(dominatingAllies[i]).brighter().brighter());

        float[][] coords1 = regions[i].getCoords();

        lines: for (int j = 0; j < coords1.length; j++) {
            int[] linkedRegions = delaunay.getLinked(i);
            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size())
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                    float[][] coords2 = regions[linkedRegion].getCoords();

                    for (int m = 0; m < coords2.length; m++) {
                        if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]
                                && ((coords1[(j + 1) % coords1.length][0] == coords2[(m + 1)
                                        % coords2.length][0]
                                        && coords1[(j + 1) % coords1.length][1] == coords2[(m + 1)
                                                % coords2.length][1])
                                        || (coords1[(j + 1)
                                                % coords1.length][0] == coords2[(m - 1 + coords2.length)
                                                        % coords2.length][0]
                                                && coords1[(j + 1)
                                                        % coords1.length][1] == coords2[(m - 1 + coords2.length)
                                                                % coords2.length][1]))) {
                            continue lines;
                        }
                    }
                }
            }

            g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]),
                    Math.round(polygons[i].xpoints[(j + 1) % coords1.length]),
                    Math.round(polygons[i].ypoints[(j + 1) % coords1.length]));
        }

        for (int j = 0; j < coords1.length; j++) {
            int neighbours = 0;
            int lastNeighbourRegion = -1;
            int neighbourCoordsIndex = -1;

            int[] linkedRegions = delaunay.getLinked(i);
            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size())
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                    float[][] coords2 = regions[linkedRegion].getCoords();

                    for (int m = 0; m < coords2.length; m++) {
                        if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]) {
                            neighbours++;
                            lastNeighbourRegion = linkedRegion;
                            neighbourCoordsIndex = m;
                            break;
                        }
                    }
                }
            }

            if (neighbours == 1) {
                g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]),
                        Math.round(polygons[lastNeighbourRegion].xpoints[neighbourCoordsIndex]),
                        Math.round(polygons[lastNeighbourRegion].ypoints[neighbourCoordsIndex]));
            }
        }
    }

    BufferedImage finalImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);

    g = (Graphics2D) finalImage.getGraphics();

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .15f));
    g.drawImage(territoriesImage, 0, 0, null);
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .5f));

    // Charge la police pour afficher le nom des alliances
    try {
        Font textFont = Font.createFont(Font.TRUETYPE_FONT,
                Action.class.getClassLoader().getResourceAsStream("fr/fg/server/resources/TinDog.ttf"));
        textFont = textFont.deriveFont(12f).deriveFont(Font.BOLD);
        g.setFont(textFont);
    } catch (Exception e) {
        LoggingSystem.getServerLogger().warn("Could not load quadrant map font.", e);
    }
    FontMetrics fm = g.getFontMetrics();

    ArrayList<Integer> closedRegions = new ArrayList<Integer>();

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0 || closedRegions.contains(i))
            continue;

        ArrayList<Integer> allyRegions = new ArrayList<Integer>();
        ArrayList<Integer> openRegions = new ArrayList<Integer>();

        openRegions.add(i);

        while (openRegions.size() > 0) {
            int currentRegion = openRegions.remove(0);
            allyRegions.add(currentRegion);
            closedRegions.add(currentRegion);

            int[] linkedRegions = delaunay.getLinked(currentRegion);

            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size() || openRegions.contains(linkedRegion)
                        || allyRegions.contains(linkedRegion))
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion])
                    openRegions.add(linkedRegion);
            }
        }

        Area area = areas.get(i);
        long xsum = 0;
        long ysum = 0;

        for (int k = 0; k < allyRegions.size(); k++) {
            int allyRegion = allyRegions.get(k);
            area = areas.get(allyRegion);

            xsum += area.getX();
            ysum += area.getY();
        }

        int x = (int) (xsum / allyRegions.size()) * MAP_SCALE + radius + 1;
        int y = (int) (-ysum / allyRegions.size()) * MAP_SCALE + radius + 1;
        ;

        Point point = new Point(x, y);
        boolean validLocation = false;
        for (int k = 0; k < allyRegions.size(); k++) {
            int allyRegion = allyRegions.get(k);

            if (polygons[allyRegion].contains(point)) {
                validLocation = true;
                break;
            }
        }

        if (validLocation) {
            if (allyRegions.size() == 1)
                y -= 14;
        } else {
            int xmid = (int) (xsum / allyRegions.size());
            int ymid = (int) (ysum / allyRegions.size());

            area = areas.get(i);
            int dx = area.getX() - xmid;
            int dy = area.getY() - ymid;
            int distance = dx * dx + dy * dy;

            int nearestAreaIndex = i;
            int nearestDistance = distance;

            for (int k = 0; k < allyRegions.size(); k++) {
                int allyRegion = allyRegions.get(k);

                area = areas.get(allyRegion);
                dx = area.getX() - xmid;
                dy = area.getY() - ymid;
                distance = dx * dx + dy * dy;

                if (distance < nearestDistance) {
                    nearestAreaIndex = allyRegion;
                    nearestDistance = distance;
                }
            }

            area = areas.get(nearestAreaIndex);
            x = area.getX() * MAP_SCALE + radius + 1;
            y = -area.getY() * MAP_SCALE + radius - 13;
        }

        // Dessine le tag de l'alliance
        String allyTag = "[ " + DataAccess.getAllyById(dominatingAllies[i]).getTag() + " ]";
        g.setColor(Color.BLACK);
        g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2 + 1, y);
        g.setColor(alliesColors.get(dominatingAllies[i]));
        g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2, y);
    }

    return finalImage;
}

From source file:rod_design_compute.ShowPanel.java

private void paintRRR(RRR rodRRR, Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setStroke(new BasicStroke(2f));

    if (rodRRR.flag2 == true || rodRRR.flag3 == true) {
        g2d.setColor(Color.red);
        if (rodRRR.flag2 == true) {
            g.drawLine(toScreenX(rodRRR.getPointB().X), toScreenY(rodRRR.getPointB().Y),
                    toScreenX(rodRRR.getPointE().X), toScreenY(rodRRR.getPointE().Y));
        } else if (rodRRR.flag3 == true) {
            g.drawLine(toScreenX(rodRRR.getPointD().X), toScreenY(rodRRR.getPointD().Y),
                    toScreenX(rodRRR.getPointE().X), toScreenY(rodRRR.getPointE().Y));
        }//  w ww . j ava 2s.  co  m
        g.drawLine(toScreenX(rodRRR.getPointC().X), toScreenY(rodRRR.getPointC().Y),
                toScreenX(rodRRR.getPointE().X), toScreenY(rodRRR.getPointE().Y));
        drawOtherPoint(rodRRR.getPointE(), g);
        g2d.setColor(Color.black);
    }

    g.drawLine(toScreenX(rodRRR.getPointB().X), toScreenY(rodRRR.getPointB().Y),
            toScreenX(rodRRR.getPointC().X), toScreenY(rodRRR.getPointC().Y));

    g.drawLine(toScreenX(rodRRR.getPointC().X), toScreenY(rodRRR.getPointC().Y),
            toScreenX(rodRRR.getPointD().X), toScreenY(rodRRR.getPointD().Y));

    drawJunctionPoint(rodRRR.getPointB(), g);
    drawJunctionPoint(rodRRR.getPointC(), g);
    drawBasePoint(rodRRR.getPointD(), g);
}

From source file:at.tuwien.ifs.somtoolbox.visualization.thematicmap.SOMRegion.java

public void drawRegion(Graphics2D g) {
    if (segments.size() > 0) {
        g.setColor(borderColor);
        g.setStroke(new BasicStroke(0.0f));
        g.drawPolygon(this);
    }// ww  w. java 2 s.co  m
}

From source file:de._13ducks.cor.graphics.GraphicsComponent.java

@Override
public void paintComponent(Graphics g) {
    //Die echte, letzendlich gltige paint-Methode, sollte nicht direkt aufgerufen werden
    // verwendet advanced Grafiktechniken, also Graphics2D Api verwenden
    Graphics2D g2 = (Graphics2D) g;
    if (modi == 2) {
        g2.setColor(Color.BLACK);
        // Editor
        // Bodentexturen rendern

        if (renderGround) {
            // OK, Boden rendern!
            runRenderRoundGround(g2);//  w w w. j  a  v a2  s .c  o  m
        }
        // Mesh rendern?
        if (renderMesh) {
            g2.setColor(Color.BLACK);
            // Mesh rendern
            for (int i = 0; i < sizeX; i++) {
                //Am oberen Rand entlanggehen, linie nach Rechts unten zeichnen
                int startX = i;
                int startY = 0;
                g2.drawLine((startX * 20) + 5, startY * 15, (sizeX * 20) + 5, ((sizeX - startX)) * 15);

                //Am oberen Rand entlanggehen, linie nach Links unten zeichnen
                g2.drawLine((startX * 20) - 10, startY * 15, -10, ((startX)) * 15);
            }

            for (int i = 0; i < sizeY; i++) {
                //Am linken Rand entlang gehen. Line nach rechts unten ziehen
                int startX = 0;
                int startY = i;

                g2.drawLine(startX * 20, (startY * 15) + 25, (sizeY - i) * 20, (sizeY * 15) + 25);
            }
        }
        if (renderBuildings) {
            // Gebude
            renderBuildings(g2);
        }

        if (renderCursor) {
            //Cursor rendern
            renderCursor(g2);
        }

        if (renderObjects) {
            // Feste Objekte
            runRenderRoundFix(g2);
        }

        if (renderCreeps) {
            // Einheiten
            renderUnits(g2);
        }
        if (renderPicCursor) {
            // Nochmal, damit es ber Einheiten schwebt (naja, leichter Pfusch)
            renderCursor(g2);
        }

    } else if (modi == 4) {
        // Debug-zeichnen
        paint_debug(g2);
    }
}

From source file:edu.gmu.cs.sim.util.media.chart.ChartGenerator.java

BufferedImage getBufferedImage() {
    // make a buffer
    if (buffer == null || buffer.getWidth(null) != chartPanel.getWidth()
            || buffer.getHeight(null) != chartPanel.getHeight()) {
        buffer = getGraphicsConfiguration().createCompatibleImage((int) chartPanel.getWidth(),
                (int) chartPanel.getHeight());
    }/*  w  ww . j av a  2 s.com*/

    // paint to the buffer
    Graphics2D g = (Graphics2D) (buffer.getGraphics());
    g.setColor(chartPanel.getBackground());
    g.fillRect(0, 0, buffer.getWidth(null), buffer.getHeight(null));
    chartPanel.paintComponent(g);
    g.dispose();
    return buffer;
}

From source file:com.igormaznitsa.mindmap.swing.panel.MindMapPanel.java

private static void drawBackground(final Graphics2D g, final MindMapPanelConfig cfg) {
    final Rectangle clipBounds = g.getClipBounds();

    if (cfg.isDrawBackground()) {
        g.setColor(cfg.getPaperColor());
        g.fillRect(clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height);

        if (cfg.isShowGrid()) {
            final double scaledGridStep = cfg.getGridStep() * cfg.getScale();

            final float minX = clipBounds.x;
            final float minY = clipBounds.y;
            final float maxX = clipBounds.x + clipBounds.width;
            final float maxY = clipBounds.y + clipBounds.height;

            g.setColor(cfg.getGridColor());

            for (float x = 0.0f; x < maxX; x += scaledGridStep) {
                if (x < minX) {
                    continue;
                }//from  w ww . j av  a 2  s.  c o m
                final int intx = Math.round(x);
                g.drawLine(intx, (int) minY, intx, (int) maxY);
            }

            for (float y = 0.0f; y < maxY; y += scaledGridStep) {
                if (y < minY) {
                    continue;
                }
                final int inty = Math.round(y);
                g.drawLine((int) minX, inty, (int) maxX, inty);
            }
        }
    }
}