Example usage for java.awt RenderingHints KEY_ANTIALIASING

List of usage examples for java.awt RenderingHints KEY_ANTIALIASING

Introduction

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

Prototype

Key KEY_ANTIALIASING

To view the source code for java.awt RenderingHints KEY_ANTIALIASING.

Click Source Link

Document

Antialiasing hint key.

Usage

From source file:haven.Utils.java

static void AA(Graphics g) {
    java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}

From source file:org.uva.itast.blended.omr.pages.PDFPageImage.java

/**
 * Mtodo que lee una imagen pdf y la transforma en un objeto de tipo
 * BufferedImage reescalado/*  w w w .  j  a v a 2 s  . c o  m*/
 * 
 * @param page
 * @return img_pdf
 * @throws InterruptedException
 * @throws Exception
 */
private BufferedImage renderFullPageImage(PDFPage page) throws InterruptedException {
    BufferedImage img_pdf = null; // bufferedimage para almacenar la imagen

    // se elige el ancho y el alto de la imagen
    int resizeWidth = OMRProcessor._PAGE_WIDTH_PIXELS;
    int resizeHeight = OMRProcessor._PAGE_HEIGHT_PIXELS;

    img_pdf = new BufferedImage(resizeWidth, resizeHeight, BufferedImage.TYPE_INT_RGB); // se configura la imagen con las
    // medidas especificas y en
    // escala de grises
    Graphics2D g2 = img_pdf.createGraphics(); // se crea un objeto grfico
    // en dos dimensiones
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    PDFRenderer renderer = new PDFRenderer(page, g2,
            new Rectangle(0, 0, OMRProcessor._PAGE_WIDTH_PIXELS, OMRProcessor._PAGE_HEIGHT_PIXELS), null,
            Color.RED); // se
    // renderiza
    // la
    // imgen
    page.waitForFinish();
    renderer.run();
    img_pdf.createGraphics().drawImage(img_pdf, 0, 0, resizeWidth, resizeHeight, null); // por ltimo se dibuja la imagen

    return img_pdf;
}

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 . jav a  2  s.c  o  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:org.kchine.r.server.impl.RGraphicsPanelRemote.java

public synchronized void paintComponent(Graphics g) {
    super.paintComponent(g);

    Dimension d = getSize();//  www. j  ava2  s.co m

    if (!d.equals(_lastSize)) {
        _lastResizeTime = System.currentTimeMillis();
        _lastSize = d;
        return;
    } else {

    }

    if (forceAntiAliasing) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }

    int i = 0, j = _l.size();
    g.setFont(_gs.f);
    g.setClip(0, 0, d.width, d.height); // reset clipping rect
    g.setColor(Color.white);
    g.fillRect(0, 0, d.width, d.height);
    while (i < j) {
        GDObject o = (GDObject) _l.elementAt(i++);
        o.paint(this, _gs, g);
    }
}

From source file:ClipImage.java

public Graphics2D createDemoGraphics2D(Graphics g) {
    Graphics2D g2 = null;//  w  w  w .  j  ava2 s  . c om

    if (offImg == null || offImg.getWidth() != w || offImg.getHeight() != h) {
        offImg = (BufferedImage) createImage(w, h);
        newBufferedImage = true;
    }

    if (offImg != null) {
        g2 = offImg.createGraphics();
        g2.setBackground(getBackground());
    }

    // .. set attributes ..
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    // .. clear canvas ..
    g2.clearRect(0, 0, w, h);

    return g2;
}

From source file:JXTransformer.java

public void paint(Graphics g) {
    //repaint the whole transformer in case the view component was repainted
    Rectangle clipBounds = g.getClipBounds();        
    if (clipBounds != null && !clipBounds.equals(visibleRect)) {
        repaint();/*from  ww  w.j av  a2s.com*/
    }
    //clear the background
    g.setColor(getBackground());
    g.fillRect(0, 0, getWidth(), getHeight());

    if (view != null && at.getDeterminant() != 0) {
        Graphics2D g2 = (Graphics2D) g.create();
        Insets insets = getInsets();
        Rectangle bounds = getBounds();
            
        //don't forget about insets
        bounds.x += insets.left;
        bounds.y += insets.top;
        bounds.width -= insets.left + insets.right;
        bounds.height -= insets.top + insets.bottom;
        double centerX1 = bounds.getCenterX();
        double centerY1 = bounds.getCenterY();

        Rectangle tb = getTransformedSize();
        double centerX2 = tb.getCenterX();
        double centerY2 = tb.getCenterY();

        //set antialiasing by default
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        if (renderingHints != null) {
            g2.addRenderingHints(renderingHints);
        }
        //translate it to the center of the view component again
        double tx = centerX1 - centerX2 - getX();
        double ty = centerY1 - centerY2 - getY();
        g2.translate((int) tx, (int) ty);
        g2.transform(at);
        view.paint(g2);
        g2.dispose();
    }
    //paint the border
    paintBorder(g);
}

From source file:com.igormaznitsa.jhexed.renders.svg.SVGImage.java

private static void processAntialias(final boolean flag, final Graphics2D g) {
    if (flag) {/* w ww .  j  a  va 2 s .  c  o m*/
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    } else {
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
        g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
    }
}

From source file:uk.ac.babraham.BamQC.Graphs.ScatterGraph.java

@Override
protected void paintComponent(Graphics g) {

    g.setColor(Color.WHITE);//from w  w  w.  j  a  va  2  s.  c om
    g.fillRect(0, 0, getWidth(), getHeight());
    g.setColor(Color.BLACK);

    if (g instanceof Graphics2D) {
        ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }

    double yStart, xStart;
    if (minY % yInterval == 0) {
        yStart = minY;
    } else {
        yStart = yInterval * (((int) minY / yInterval) + 1);
    }

    if (minX % xInterval == 0) {
        xStart = minX;
    } else {
        xStart = xInterval * (((int) minX / xInterval) + 1);
    }

    int xOffset = 0;

    // Draw the yLabel on the left of the yAxis
    int yLabelRightShift = 12;
    if (yLabel == null || yLabel.isEmpty()) {
        yLabelRightShift = 0;
    } else {
        if (g instanceof Graphics2D) {
            Graphics2D g2 = (Graphics2D) g;
            AffineTransform orig = g2.getTransform();
            g2.rotate(-Math.PI / 2);
            g2.setColor(Color.BLACK);
            g2.drawString(yLabel, -getY(-yInterval) / 2 - (g.getFontMetrics().stringWidth(yLabel) / 2),
                    yLabelRightShift);
            g2.setTransform(orig);
        }
    }

    // Draw the y axis labels
    int lastYLabelEnd = Integer.MAX_VALUE;
    for (double i = yStart; i <= maxY; i += yInterval) {
        String label = "" + i;
        label = label.replaceAll(".0$", ""); // Don't leave trailing .0s where we don't need them.
        // Calculate the new xOffset depending on the widest ylabel.
        int width = g.getFontMetrics().stringWidth(label);
        if (width > xOffset) {
            xOffset = width;
        }
        // place the y axis labels so that they don't overlap when the plot is resized.
        int baseNumberHeight = g.getFontMetrics().getHeight();
        int baseNumberPosition = getY(i) + (baseNumberHeight / 2);
        if (baseNumberPosition + baseNumberHeight < lastYLabelEnd) {
            // Draw the y axis labels
            g.drawString(label, yLabelRightShift + 6, baseNumberPosition);
            lastYLabelEnd = baseNumberPosition + 2;
        }
    }

    // Give the x axis a bit of breathing space
    xOffset = xOffset + yLabelRightShift + 8;

    // Now draw horizontal lines across from the y axis
    g.setColor(new Color(180, 180, 180));
    for (double i = yStart; i <= maxY; i += yInterval) {
        g.drawLine(xOffset, getY(i), getWidth() - 10, getY(i));
    }
    g.setColor(Color.BLACK);

    // Draw the graph title
    int titleWidth = g.getFontMetrics().stringWidth(graphTitle);
    g.drawString(graphTitle, (xOffset + ((getWidth() - (xOffset + 10)) / 2)) - (titleWidth / 2), 30);

    // Draw the xLabel under the xAxis
    g.drawString(xLabel, (getWidth() / 2) - (g.getFontMetrics().stringWidth(xLabel) / 2), getHeight() - 5);

    // Now draw the data points
    double baseWidth = (getWidth() - (xOffset + 10)) / (maxX - minX);

    //      System.out.println("Base Width is "+baseWidth);
    // Let's find the longest label, and then work out how often we can draw labels
    int lastXLabelEnd = 0;

    // Draw the x axis labels
    for (double i = xStart; i <= maxX; i += xInterval) {
        g.setColor(Color.BLACK);
        String baseNumber = "" + i;
        baseNumber = baseNumber.replaceAll(".0$", ""); // Don't leave trailing .0s where we don't need them.
        // Calculate the new xOffset depending on the widest ylabel.
        int baseNumberWidth = g.getFontMetrics().stringWidth(baseNumber);
        int baseNumberPosition = (int) (xOffset + (baseWidth * i) - (baseNumberWidth / 2));

        if (baseNumberPosition > lastXLabelEnd) {
            g.drawString(baseNumber, baseNumberPosition, getHeight() - 25);
            lastXLabelEnd = baseNumberPosition + baseNumberWidth + 5;
        }
        // Now draw vertical lines across from the y axis
        g.setColor(new Color(180, 180, 180));
        g.drawLine((int) (xOffset + (baseWidth * i)), getHeight() - 40, (int) (xOffset + (baseWidth * i)), 40);
        g.setColor(Color.BLACK);
    }

    // Now draw the axes
    g.drawLine(xOffset, getHeight() - 40, getWidth() - 10, getHeight() - 40);
    g.drawLine(xOffset, getHeight() - 40, xOffset, 40);

    // Initialise the arrays containing the tooltips
    rectangles = new ArrayList<Rectangle>();
    tips = new ArrayList<String>();

    g.setColor(Color.BLUE);
    // Draw the data points
    double ovalSize = 5;
    // We distinguish two inputs since the x label does not start from 0.
    // used for computing the actual line points as if they were starting from 0.
    double[] inputVar = new double[data.length];
    double[] responseVar = new double[data.length];
    for (int d = 0; d < data.length; d++) {
        double x = getX(xCategories[d], xOffset) - ovalSize / 2;
        double y = getY(data[d]) - ovalSize / 2;
        g.fillOval((int) x, (int) y, (int) (ovalSize), (int) (ovalSize));
        g.drawString(toolTipLabels[d], (int) x + 2, (int) y + 16);
        inputVar[d] = Double.valueOf(xCategories[d]);
        responseVar[d] = data[d];

        // Tool tips
        Rectangle r = new Rectangle((int) x, (int) y, (int) (ovalSize), (int) (ovalSize));
        rectangles.add(r);
        tips.add(toolTipLabels[d]);
    }
    g.setColor(Color.BLACK);

    // Draw the intercept 

    // WARNING: Is drawing a least squares regression line asserting that "the distribution follows a power law" correct?
    // This is our case if we plot log-log..
    // It seems not in this paper (Appendix A) http://arxiv.org/pdf/0706.1062v2.pdf

    if (data.length > 1) {
        LinearRegression linReg = new LinearRegression(inputVar, responseVar);
        double intercept = linReg.intercept();
        double slope = linReg.slope();
        double rSquare = linReg.R2();

        // Let's now calculate the two points (x1, y1) and (xn, yn)
        // (x1, y1). We need to skip the areas where x1<minY and y1>maxY
        double x1 = minX;
        double y1 = slope * minX + intercept;
        if (y1 < minY) {
            x1 = (minY - intercept) / slope;
            y1 = minY;
        } else if (y1 > maxY) {
            x1 = (maxY - intercept) / slope;
            y1 = maxY;
        }
        // (xn, yn). maxX which essentially is inputVar[inputVar.length-1]
        double xn = maxX;
        double yn = slope * maxX + intercept;

        if (g instanceof Graphics2D) {
            ((Graphics2D) g).setStroke(new BasicStroke(1.5f));
        }
        g.setColor(Color.RED);
        g.drawLine(getX(x1, xOffset), getY(y1), getX(xn, xOffset), getY(yn));
        g.setColor(Color.BLACK);
        if (g instanceof Graphics2D) {
            ((Graphics2D) g).setStroke(new BasicStroke(1));
        }

        // Draw the legend for the intercept
        String legendString = "y = " + Precision.round(slope, 3) + "x";
        if (intercept < 0)
            legendString += " - " + Precision.round(-intercept, 3);
        else
            legendString += " + " + Precision.round(intercept, 3);
        int width = g.getFontMetrics().stringWidth(legendString);

        // First draw a box to put the legend in
        g.setColor(Color.WHITE);
        g.fillRect(xOffset + 10, 45, width + 8, 35);
        g.setColor(Color.LIGHT_GRAY);
        g.drawRect(xOffset + 10, 45, width + 8, 35);

        // Now draw the legend label
        g.setColor(Color.RED);
        g.drawString(legendString, xOffset + 13, 60);
        g.drawString("R^2 = " + Precision.round(rSquare, 3), xOffset + 13, 76);
        g.setColor(Color.BLACK);
    }

}

From source file:com.ctsim.simemua_instructor.ACarControlPanelFrame.java

private void initGraphics() {
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    try {//ww  w . ja  va2 s  .  c  om
        x = (int) viewPanel.getMousePosition().getX();
        y = (int) viewPanel.getMousePosition().getY();

    } catch (Exception ex) {
        x = 0;
        y = 0;
    }

    g2.drawImage(aCarControlPanelImg, null, this);
    //drawDevices();
    drawSwitchRotary();

    g2.drawString("(" + x + ", " + y + ")", 10, 10);
}

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  .jav  a 2  s.c  om*/
    }

    //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();
    }

}