Example usage for java.awt Graphics fillRect

List of usage examples for java.awt Graphics fillRect

Introduction

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

Prototype

public abstract void fillRect(int x, int y, int width, int height);

Source Link

Document

Fills the specified rectangle.

Usage

From source file:org.deegree.ogcwebservices.wms.dataaccess.ID2PInterpolation.java

public BufferedImage perform(GetLegendGraphic glg) {

    BufferedImage bi = new BufferedImage(150, colorMap.size() * 25, BufferedImage.TYPE_4BYTE_ABGR);
    Iterator<double[]> iterator = colorMap.keySet().iterator();
    List<double[]> list = new ArrayList<double[]>(colorMap.size());

    while (iterator.hasNext()) {
        double[] ds = iterator.next();
        list.add(ds);/*from  ww w .  j av  a 2  s . com*/
    }

    for (int i = list.size() - 1; 0 <= i; i--) {
        for (int j = 0; j < i; j++) {
            if (list.get(j + 1)[0] < list.get(j)[0]) {
                double[] ds = list.get(j + 1);
                list.set(j + 1, list.get(j));
                list.set(j, ds);
            }
        }
    }

    int i = 0;
    Graphics g = bi.getGraphics();
    for (double[] ds : list) {
        Color color = colorMap.get(ds);
        g.setColor(color);
        g.fillRect(2, 2 + i * 25, 20, 20);
        g.setColor(Color.BLACK);
        g.drawRect(2, 2 + i * 25, 20, 20);
        g.drawString(Double.toString(ds[0]) + " - " + Double.toString(ds[1]), 25, 17 + i * 25);
        i++;
    }
    g.dispose();
    return bi;

}

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

@Override
protected void paintComponent(Graphics g) {

    g.setColor(Color.WHITE);//from w  w w  .  ja  v a  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:org.squale.squaleweb.applicationlayer.action.export.ppt.PPTData.java

/**
 * Convert a html code to an image/*from   w w  w.  ja  v  a  2s.  co m*/
 * 
 * @param html html to convert
 * @return html converted to png
 * @throws IOException if error
 * @throws PPTGeneratorException 
 */
protected byte[] htmlToImage(String html) throws IOException, PPTGeneratorException {
    try {
        JEditorPane editor = new JEditorPane();
        editor.setContentType("text/html");
        editor.setText(html);
        editor.setSize(editor.getPreferredSize());
        editor.addNotify();
        LOGGER.debug("Panel is built");
        BufferedImage bufferSave = new BufferedImage(editor.getPreferredSize().width,
                editor.getPreferredSize().height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics g = bufferSave.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, editor.getPreferredSize().width, editor.getPreferredSize().height);
        editor.paint(g);
        LOGGER.debug("graphics is drawn");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(bufferSave, "png", out);
        return out.toByteArray();
    } catch (HeadlessException e) {
        LOGGER.error("X Server no initialized or -Djava.awt.headless=true not set !");
        throw new PPTGeneratorException("X Server no initialized or -Djava.awt.headless=true not set !");
    }
}

From source file:org.squale.squaleweb.applicationlayer.action.export.ppt.PPTData.java

/**
 * Add an image with a html code without change its dimension
 * //from   ww  w  .ja v a  2 s  . co m
 * @param slideToSet slide to set
 * @param html html code
 * @param x horizontal position
 * @param y vertical position
 * @throws IOException if error
 * @throws PPTGeneratorException 
 */
protected void addHtmlPicture(Slide slideToSet, String html, int x, int y)
        throws IOException, PPTGeneratorException {
    try {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        if (!ge.isHeadlessInstance()) {
            LOGGER.warn("Runtime is not configured for supporting graphiv manipulation !");
        }
        JEditorPane editor = new JEditorPane();
        editor.setContentType("text/html");
        editor.setText(html);
        LOGGER.debug("Editor pane is built");
        editor.setSize(editor.getPreferredSize());
        editor.addNotify(); // Serveur X requis
        LOGGER.debug("Panel rendering is done");
        BufferedImage bufferSave = new BufferedImage(editor.getPreferredSize().width,
                editor.getPreferredSize().height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics g = bufferSave.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, editor.getPreferredSize().width, editor.getPreferredSize().height);
        editor.paint(g);
        LOGGER.debug("graphics is drawn");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(bufferSave, "png", out);
        LOGGER.debug("image is written");
        addPicture(slideToSet, out.toByteArray(),
                new Rectangle(x, y, editor.getPreferredSize().width, editor.getPreferredSize().height));
        LOGGER.debug("image is added");
    } catch (HeadlessException e) {
        LOGGER.error("X Server no initialized or -Djava.awt.headless=true not set !");
        throw new PPTGeneratorException("X Server no initialized or -Djava.awt.headless=true not set !");
    }
}

From source file:ColorVariousObjects.java

public void paint(Graphics g) {
    Color c1 = new Color(255, 100, 100);
    Color c2 = new Color(100, 255, 100);
    Color c3 = new Color(100, 100, 255);

    g.setColor(c1);/*  w w  w  .  ja  v a  2 s  . c  o m*/
    g.drawLine(0, 0, 100, 100);
    g.drawLine(0, 100, 100, 0);

    g.setColor(c2);
    g.drawLine(40, 25, 250, 180);
    g.drawLine(75, 90, 400, 400);

    g.setColor(c3);
    g.drawLine(20, 150, 400, 40);
    g.drawLine(5, 290, 80, 19);

    g.setColor(Color.red);
    g.drawOval(10, 10, 50, 50);
    g.fillOval(70, 90, 140, 100);

    g.setColor(Color.blue);
    g.drawOval(190, 10, 90, 30);
    g.drawRect(10, 10, 60, 50);

    g.setColor(Color.cyan);
    g.fillRect(100, 10, 60, 50);
    g.drawRoundRect(190, 10, 60, 50, 15, 15);
}

From source file:fr.ign.cogit.geoxygene.appli.layer.LayerViewAwtPanel.java

@Override
public final void paintComponent(final Graphics g) {
    try {//from   w w  w  .  j av a 2  s.c  o  m
        ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // // super.paintComponent(g);
        // // clear the graphics
        g.setColor(this.getBackground());
        g.fillRect(0, 0, this.getWidth(), this.getHeight());
        // copy the result of the rendering manager to the panel
        this.getRenderingManager().copyTo((Graphics2D) g);
        // if currently editing geometry
        this.paintGeometryEdition(g);
        this.paintOverlays(g);
        //
        if (this.recording) {
            this.saveImage();
        }
    } catch (Throwable t) {
        LayerViewAwtPanel.logger.error(I18N.getString("LayerViewAwtPanel.PaintError")); //$NON-NLS-1$
        t.printStackTrace();
        // TODO HANDLE EXCEPTIONS
    }
}

From source file:ExtendedParagraphExample.java

public void paint(Graphics g, Shape a) {
    Container comp = getContainer();
    Rectangle alloc = new Rectangle(a.getBounds());

    alloc.x += paraInsets.left;/*from  www .  j  a va 2s . co  m*/
    alloc.y += paraInsets.top;
    alloc.width -= paraInsets.left + paraInsets.right;
    alloc.height -= paraInsets.top + paraInsets.bottom;

    if (bgColor != null) {
        Color origColor = g.getColor();
        g.setColor(bgColor);
        g.fillRect(alloc.x, alloc.y, alloc.width, alloc.height);
        g.setColor(origColor);
    }

    if (border != null) {
        // Paint the border
        border.paintBorder(comp, g, alloc.x, alloc.y, alloc.width, alloc.height);
    }
    super.paint(g, a); // Note: pass ORIGINAL allocation
}

From source file:uk.co.modularaudio.mads.base.waveroller.ui.WaveRollerDisplayUiJComponent.java

@Override
public void paint(final Graphics g) {
    if (rollPainter != null) {
        if (rollPainter.buffer0Visible()) {
            g.drawImage(rollPainter.buffer0.bi, rollPainter.buffer0XOffset, 0, null);
        }//from  w ww  .  ja  v  a  2s. c  o  m
        if (rollPainter.buffer1Visible()) {
            g.drawImage(rollPainter.buffer1.bi, rollPainter.buffer1XOffset, 0, null);
        }
    } else {
        g.setColor(WaveRollerColours.BACKGROUND_COLOR);
        final Rectangle b = getBounds();
        g.fillRect(0, 0, b.width, b.height);
    }
}

From source file:JavaXWin.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    m_height = getHeight();/*from ww  w.j  av a2 s .c om*/
    m_width = getWidth();
    g.setColor(C_BACKGROUND);
    g.fillRect(0, 0, m_width, m_height);
    Component[] components = m_desktop.getComponents();
    m_widthratio = ((float) m_desktop.getWidth()) / ((float) m_width);
    m_heightratio = ((float) m_desktop.getHeight()) / ((float) m_height);
    for (int i = components.length - 1; i > -1; i--) {
        if (components[i].isVisible()) {
            g.setColor(C_UNSELECTED);
            if (components[i] instanceof JInternalFrame) {
                if (((JInternalFrame) components[i]).isSelected())
                    g.setColor(C_SELECTED);
            } else if (components[i] instanceof WindowWatcher)
                g.setColor(C_WWATCHER);
            g.fillRect((int) (((float) components[i].getX()) / m_widthratio),
                    (int) (((float) components[i].getY()) / m_heightratio),
                    (int) (((float) components[i].getWidth()) / m_widthratio),
                    (int) (((float) components[i].getHeight()) / m_heightratio));
            g.setColor(Color.black);
            g.drawRect((int) (((float) components[i].getX()) / m_widthratio),
                    (int) (((float) components[i].getY()) / m_heightratio),
                    (int) (((float) components[i].getWidth()) / m_widthratio),
                    (int) (((float) components[i].getHeight()) / m_heightratio));
        }
    }
    g.drawLine(m_width / 2, 0, m_width / 2, m_height);
    g.drawLine(0, m_height / 2, m_width, m_height / 2);
}

From source file:javazoom.jlgui.player.amp.visual.ui.SpectrumTimeAnalyzer.java

public synchronized void process(float[] pLeft, float[] pRight, float pFrameRateRatioHint) {
    if (displayMode == DISPLAY_MODE_OFF)
        return;/*from w  w w  .  j  a v a  2 s.c o m*/
    Graphics wGrp = getDoubleBuffer().getGraphics();
    wGrp.setColor(getBackground());
    wGrp.fillRect(0, 0, getSize().width, getSize().height);
    switch (displayMode) {
    case DISPLAY_MODE_SCOPE:
        drawScope(wGrp, stereoMerge(pLeft, pRight));
        break;
    case DISPLAY_MODE_SPECTRUM_ANALYSER:
        drawSpectrumAnalyser(wGrp, stereoMerge(pLeft, pRight), pFrameRateRatioHint);
        break;
    case DISPLAY_MODE_OFF:
        drawVUMeter(wGrp, pLeft, pRight, pFrameRateRatioHint);
        break;
    }
    // -- Show FPS if necessary.
    if (showFPS) {
        // -- Calculate FPS.
        if (System.currentTimeMillis() >= lfu + 1000) {
            lfu = System.currentTimeMillis();
            fps = fc;
            fc = 0;
        }
        fc++;
        wGrp.setColor(Color.yellow);
        wGrp.drawString("FPS: " + fps + " (FRRH: " + pFrameRateRatioHint + ")", 0, height - 1);
    }
    if (getGraphics() != null)
        getGraphics().drawImage(getDoubleBuffer(), 0, 0, null);
    //      repaint();
    //      try {
    //          EventQueue.invokeLater( new AWTPaintSynchronizer() );
    //      } catch ( Exception pEx ) {
    //          // -- Ignore exception.
    //          pEx.printStackTrace();
    //      }
}