Example usage for java.awt Graphics2D setFont

List of usage examples for java.awt Graphics2D setFont

Introduction

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

Prototype

public abstract void setFont(Font font);

Source Link

Document

Sets this graphics context's font to the specified font.

Usage

From source file:edu.dlnu.liuwenpeng.render.BarRenderer.java

/**    
* Draws an item label.  This method is overridden so that the bar can be    
* used to calculate the label anchor point.    
*    //from   w  w w.ja  va  2s . c  o  m
* @param g2  the graphics device.    
* @param data  the dataset.    
* @param row  the row.    
* @param column  the column.    
* @param plot  the plot.    
* @param generator  the label generator.    
* @param bar  the bar.    
* @param negative  a flag indicating a negative value.    
*/
protected void drawItemLabel(Graphics2D g2, CategoryDataset data, int row, int column, CategoryPlot plot,
        CategoryItemLabelGenerator generator, Rectangle2D bar, boolean negative) {

    String label = generator.generateLabel(data, row, column);
    if (label == null) {
        return; // nothing to do    
    }

    Font labelFont = getItemLabelFont(row, column);
    g2.setFont(labelFont);
    Paint paint = getItemLabelPaint(row, column);
    g2.setPaint(paint);

    // find out where to place the label...    
    ItemLabelPosition position = null;
    if (!negative) {
        position = getPositiveItemLabelPosition(row, column);
    } else {
        position = getNegativeItemLabelPosition(row, column);
    }

    // work out the label anchor point...    
    Point2D anchorPoint = calculateLabelAnchorPoint(position.getItemLabelAnchor(), bar, plot.getOrientation());

    if (isInternalAnchor(position.getItemLabelAnchor())) {
        Shape bounds = TextUtilities.calculateRotatedStringBounds(label, g2, (float) anchorPoint.getX(),
                (float) anchorPoint.getY(), position.getTextAnchor(), position.getAngle(),
                position.getRotationAnchor());

        if (bounds != null) {
            if (!bar.contains(bounds.getBounds2D())) {
                if (!negative) {
                    position = getPositiveItemLabelPositionFallback();
                } else {
                    position = getNegativeItemLabelPositionFallback();
                }
                if (position != null) {
                    anchorPoint = calculateLabelAnchorPoint(position.getItemLabelAnchor(), bar,
                            plot.getOrientation());
                }
            }
        }

    }

    if (position != null) {
        TextUtilities.drawRotatedString(label, g2, (float) anchorPoint.getX(), (float) anchorPoint.getY(),
                position.getTextAnchor(), position.getAngle(), position.getRotationAnchor());
    }
}

From source file:juicebox.track.EigenvectorTrack.java

/**
 * Render the track in the supplied rectangle.  It is the responsibility of the track to draw within the
 * bounds of the rectangle./*  w w  w. j  a va  2s .  c om*/
 *
 * @param g2d      the graphics context
 * @param rect     the track bounds, relative to the enclosing DataPanel bounds.
 * @param gridAxis
 */

@Override
public void render(Graphics2D g2d, Context context, Rectangle rect, TrackPanel.Orientation orientation,
        HiCGridAxis gridAxis) {

    g2d.setColor(color);

    int height = orientation == TrackPanel.Orientation.X ? rect.height : rect.width;
    int width = orientation == TrackPanel.Orientation.X ? rect.width : rect.height;
    int y = orientation == TrackPanel.Orientation.X ? rect.y : rect.x;
    int x = orientation == TrackPanel.Orientation.X ? rect.x : rect.y;

    MatrixZoomData zd;
    try {
        zd = hic.getZd();
    } catch (Exception e) {
        return;
    }

    int zoom = zd.getZoom().getBinSize();
    if (zoom != currentZoom) {
        clearDataCache();
    }

    int chrIdx = orientation == TrackPanel.Orientation.X ? zd.getChr1Idx() : zd.getChr2Idx();
    double[] eigen = dataCache.get(chrIdx);
    if (eigen == null) {
        eigen = hic.getEigenvector(chrIdx, 0);
        currentZoom = zoom;
        setData(chrIdx, eigen);
    }

    if (eigen == null || eigen.length == 0) {
        Font original = g2d.getFont();
        g2d.setFont(FontManager.getFont(12));

        if (orientation == TrackPanel.Orientation.X) {
            GraphicUtils.drawCenteredText("Eigenvector not available at this resolution", rect, g2d);
        } else {
            drawRotatedString(g2d, "Eigenvector not available at this resolution", (2 * rect.height) / 3,
                    rect.x + 15);
        }

        g2d.setFont(original);
        return;
    }

    double dataMax = dataMaxCache.get(chrIdx);
    double median = medianCache.get(chrIdx);

    int h = height / 2;

    for (int bin = (int) context.getBinOrigin(); bin < eigen.length; bin++) {

        if (Double.isNaN(eigen[bin]))
            continue;

        int xPixelLeft = x + (int) ((bin - context.getBinOrigin()) * hic.getScaleFactor());
        int xPixelRight = x + (int) ((bin + 1 - context.getBinOrigin()) * hic.getScaleFactor());

        if (xPixelRight < x) {
            continue;
        } else if (xPixelLeft > x + width) {
            break;
        }

        double x2 = eigen[bin] - median;
        double max = dataMax - median;

        int myh = (int) ((x2 / max) * h);
        if (x2 > 0) {
            g2d.fillRect(xPixelLeft, y + h - myh, (xPixelRight - xPixelLeft), myh);
        } else {
            g2d.fillRect(xPixelLeft, y + h, (xPixelRight - xPixelLeft), -myh);
        }
    }

}

From source file:edu.dlnu.liuwenpeng.render.NewXYBarRenderer.java

/**    
* Draws an item label.  This method is provided as an alternative to    
* {@link #drawItemLabel(Graphics2D, PlotOrientation, XYDataset, int, int,     
* double, double, boolean)} so that the bar can be used to calculate the     
* label anchor point.     //  w  w  w.j  a va2 s .c  o m
*     
* @param g2  the graphics device.    
* @param dataset  the dataset.    
* @param series  the series index.    
* @param item  the item index.    
* @param plot  the plot.    
* @param generator  the label generator (<code>null</code> permitted, in     
*         which case the method does nothing, just returns).    
* @param bar  the bar.    
* @param negative  a flag indicating a negative value.    
*/
protected void drawItemLabel(Graphics2D g2, XYDataset dataset, int series, int item, XYPlot plot,
        XYItemLabelGenerator generator, Rectangle2D bar, boolean negative) {

    if (generator == null) {
        return; // nothing to do    
    }
    String label = generator.generateLabel(dataset, series, item);
    if (label == null) {
        return; // nothing to do       
    }

    Font labelFont = getItemLabelFont(series, item);
    g2.setFont(labelFont);
    Paint paint = getItemLabelPaint(series, item);
    g2.setPaint(paint);

    // find out where to place the label...    
    ItemLabelPosition position = null;
    if (!negative) {
        position = getPositiveItemLabelPosition(series, item);
    } else {
        position = getNegativeItemLabelPosition(series, item);
    }

    // work out the label anchor point...    
    Point2D anchorPoint = calculateLabelAnchorPoint(position.getItemLabelAnchor(), bar, plot.getOrientation());

    if (isInternalAnchor(position.getItemLabelAnchor())) {
        Shape bounds = TextUtilities.calculateRotatedStringBounds(label, g2, (float) anchorPoint.getX(),
                (float) anchorPoint.getY(), position.getTextAnchor(), position.getAngle(),
                position.getRotationAnchor());

        if (bounds != null) {
            if (!bar.contains(bounds.getBounds2D())) {
                if (!negative) {
                    position = getPositiveItemLabelPositionFallback();
                } else {
                    position = getNegativeItemLabelPositionFallback();
                }
                if (position != null) {
                    anchorPoint = calculateLabelAnchorPoint(position.getItemLabelAnchor(), bar,
                            plot.getOrientation());
                }
            }
        }

    }

    if (position != null) {
        TextUtilities.drawRotatedString(label, g2, (float) anchorPoint.getX(), (float) anchorPoint.getY(),
                position.getTextAnchor(), position.getAngle(), position.getRotationAnchor());
    }
}

From source file:org.jcurl.core.swing.WCComponent.java

private BufferedImage renderPng(final String watermark) {
    final BufferedImage img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
    final Graphics2D g2 = (Graphics2D) img.getGraphics();
    {//from   w  w w .jav a  2s.co m
        final Map<Key, Object> hints = new HashMap<Key, Object>();
        hints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        hints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        hints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        hints.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        hints.put(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
        hints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.addRenderingHints(hints);
    }
    final Font f0 = g2.getFont();
    paint(g2);
    g2.setTransform(new AffineTransform());
    if (watermark != null) {
        if (log.isDebugEnabled())
            log.debug(f0);
        g2.setFont(f0);
        g2.setColor(new Color(0, 0, 0, 128));
        g2.drawString(watermark, 10, 20);
    }
    g2.dispose();
    return img;
}

From source file:edu.ku.brc.af.ui.forms.validation.ValFormattedTextField.java

/**
 * Creates the various UI Components for the formatter.
 *///w w  w.jav a  2  s.  c  o m
protected void createUI() {
    CellConstraints cc = new CellConstraints();

    if (isViewOnly
            || (formatter != null && !formatter.isUserInputNeeded() && fields != null && fields.size() == 1)) {
        viewtextField = new JTextField();
        setControlSize(viewtextField);

        // Remove by rods 12/5/08 this messes thihngs up
        // values don't get inserted correctly, shouldn't be needed anyway

        //JFormattedDoc document = new JFormattedDoc(viewtextField, formatter, formatter.getFields().get(0));
        //viewtextField.setDocument(document);
        //document.addDocumentListener(this);
        //documents.add(document);

        ViewFactory.changeTextFieldUIForDisplay(viewtextField, false);
        PanelBuilder builder = new PanelBuilder(new FormLayout("1px,f:p:g,1px", "1px,f:p:g,1px"), this);
        builder.add(viewtextField, cc.xy(2, 2));
        bgColor = viewtextField.getBackground();

    } else {
        JTextField txt = new JTextField();

        Font txtFont = txt.getFont();

        Font font = new Font("Courier", Font.PLAIN, txtFont.getSize());

        BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        g.setFont(font);
        FontMetrics fm = g.getFontMetrics(font);
        g.dispose();

        Insets ins = txt.getBorder().getBorderInsets(txt);
        int baseWidth = ins.left + ins.right;

        bgColor = txt.getBackground();

        StringBuilder sb = new StringBuilder("1px");
        for (UIFieldFormatterField f : fields) {
            sb.append(",");
            if (f.getType() == FieldType.separator || f.getType() == FieldType.constant) {
                sb.append('p');
            } else {
                sb.append(((fm.getMaxAdvance() * f.getSize()) + baseWidth) + "px");
            }
        }
        sb.append(",1px");
        PanelBuilder builder = new PanelBuilder(new FormLayout(sb.toString(), "1px,P:G,1px"), this);

        comps = new JComponent[fields.size()];
        int inx = 0;
        for (UIFieldFormatterField f : fields) {
            JComponent comp = null;
            JComponent tfToAdd = null;

            if (f.getType() == FieldType.separator || f.getType() == FieldType.constant) {
                comp = createLabel(f.getValue());
                if (f.getType() == FieldType.constant) {
                    comp.setBackground(Color.WHITE);
                    comp.setOpaque(true);
                }
                tfToAdd = comp;

            } else {
                JTextField tf = new BGTextField(f.getSize(), isViewOnly ? "" : f.getValue());
                tfToAdd = tf;

                if (inx == 0) {
                    tf.addKeyListener(new KeyAdapter() {
                        @Override
                        public void keyPressed(KeyEvent e) {
                            checkForPaste(e);
                        }
                    });
                }

                JFormattedDoc document = new JFormattedDoc(tf, formatter, f);
                tf.setDocument(document);
                document.addDocumentListener(new DocumentAdaptor() {
                    @Override
                    protected void changed(DocumentEvent e) {
                        isChanged = true;
                        if (!shouldIgnoreNotifyDoc) {
                            String fldStr = getText();
                            int len = StringUtils.isNotEmpty(fldStr) ? fldStr.length() : 0;
                            if (formatter != null && len > 0 && formatter.isLengthOK(len)) {
                                setState(formatter.isValid(fldStr) ? UIValidatable.ErrorType.Valid
                                        : UIValidatable.ErrorType.Error);
                                repaint();
                            }

                            //validateState();
                            if (changeListener != null) {
                                changeListener.stateChanged(new ChangeEvent(this));
                            }

                            if (documentListeners != null) {
                                for (DocumentListener dl : documentListeners) {
                                    dl.changedUpdate(null);
                                }
                            }
                        }
                        currCachedValue = null;
                    }
                });
                documents.add(document);

                addFocusAdapter(tf);

                comp = tf;
                comp.setFont(font);

                if (f.isIncrementer()) {
                    editTF = tf;
                    cardLayout = new CardLayout();
                    cardPanel = new JPanel(cardLayout);
                    cardPanel.add("edit", tf);

                    viewTF = new BGTextField(f.getSize(), isViewOnly ? "" : f.getValue());
                    viewTF.setDocument(document);
                    cardPanel.add("view", viewTF);

                    cardLayout.show(cardPanel, "view");
                    comp = cardPanel;
                    tfToAdd = cardPanel;
                }
            }

            setControlSize(tfToAdd);
            builder.add(comp, cc.xy(inx + 2, 2));
            comps[inx] = tfToAdd;
            inx++;
        }
    }
}

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

private void drawMessageHelper(Graphics2D g2, String message, Font font, int w, int h, int offset) {
    g2.setFont(font);
    FontMetrics metrics = g2.getFontMetrics();

    Rectangle2D stringBounds = font.getStringBounds(message, g2.getFontRenderContext());

    int preferredWidth = (int) stringBounds.getWidth() + metrics.getHeight();
    int preferredHeight = (int) stringBounds.getHeight() + metrics.getHeight();

    w = Math.min(preferredWidth, w);
    h = Math.min(preferredHeight, h);

    int x = (getWidth() - (int) stringBounds.getWidth()) / 2;
    int y = (getHeight() / 2) + ((metrics.getAscent() - metrics.getDescent()) / 2) + offset;

    g2.drawString(message, x, y);/*from  ww w.  ja  v  a  2 s. co m*/
}

From source file:org.cruk.mga.CreateReport.java

/**
 * Draws the x-axis for the number of sequences and the legend.
 *
 * @param g2/*from www.  j  av  a  2 s .  c o  m*/
 * @param x0
 * @param y
 * @param tickIntervals
 * @param maxSequenceCount
 * @return
 */
private int drawAxisAndLegend(Graphics2D g2, int x0, int y, int tickIntervals, long maxSequenceCount) {
    g2.setColor(Color.BLACK);
    g2.setFont(axisFont);

    boolean millions = maxSequenceCount / tickIntervals >= 1000000;
    long largestTickValue = maxSequenceCount;
    if (millions)
        largestTickValue /= 1000000;
    int w = g2.getFontMetrics().stringWidth(Long.toString(largestTickValue));
    int x1 = plotWidth - (w / 2) - gapSize;
    g2.drawLine(x0, y, x1, y);

    int tickFontHeight = g2.getFontMetrics().getAscent();
    int tickHeight = tickFontHeight / 2;
    for (int i = 0; i <= tickIntervals; i++) {
        int x = x0 + i * (x1 - x0) / tickIntervals;
        g2.drawLine(x, y, x, y + tickHeight);
        long tickValue = i * maxSequenceCount / tickIntervals;
        if (millions)
            tickValue /= 1000000;
        String s = Long.toString(tickValue);
        int xs = x - g2.getFontMetrics().stringWidth(s) / 2 + 1;
        int ys = y + tickHeight + tickFontHeight + 1;
        g2.drawString(s, xs, ys);
    }

    g2.setFont(font);
    int fontHeight = g2.getFontMetrics().getAscent();
    String s = "Number of sequences";
    if (millions)
        s += " (millions)";
    int xs = x0 + (x1 - x0 - g2.getFontMetrics().stringWidth(s)) / 2;
    int ys = y + tickHeight + tickFontHeight + fontHeight + fontHeight / 3;
    g2.drawString(s, xs, ys);

    int yl = ys + fontHeight * 2;
    int xl = x0;

    int barHeight = (int) (fontHeight * 0.7f);
    int barWidth = 3 * barHeight;
    int yb = yl + (int) (fontHeight * 0.3f);
    int gap = (int) (fontHeight * 0.4f);

    g2.setColor(Color.GREEN);
    g2.fillRect(xl, yb, barWidth, barHeight);
    g2.setColor(Color.BLACK);
    g2.drawRect(xl, yb, barWidth, barHeight);
    g2.setFont(axisFont);
    String label = "Sequenced species/genome";
    xl += barWidth + gap;
    g2.drawString(label, xl, yl + fontHeight);
    xl += g2.getFontMetrics().stringWidth(label) + gap * 3;

    g2.setColor(Color.ORANGE);
    g2.fillRect(xl, yb, barWidth, barHeight);
    g2.setColor(Color.BLACK);
    g2.drawRect(xl, yb, barWidth, barHeight);
    label = "Control";
    xl += barWidth + gap;
    g2.drawString(label, xl, yl + fontHeight);
    xl += g2.getFontMetrics().stringWidth(label) + gap * 3;

    g2.setColor(Color.RED);
    g2.fillRect(xl, yb, barWidth, barHeight);
    g2.setColor(Color.BLACK);
    g2.drawRect(xl, yb, barWidth, barHeight);
    label = "Contaminant";
    xl += barWidth + gap;
    g2.drawString(label, xl, yl + fontHeight);
    xl += g2.getFontMetrics().stringWidth(label) + gap * 3;

    g2.setColor(ADAPTER_COLOR);
    g2.fillRect(xl, yb, barWidth, barHeight);
    g2.setColor(Color.BLACK);
    g2.drawRect(xl, yb, barWidth, barHeight);
    label = "Adapter";
    xl += barWidth + gap;
    g2.drawString(label, xl, yl + fontHeight);
    xl += g2.getFontMetrics().stringWidth(label) + gap * 3;

    g2.setColor(Color.BLACK);
    g2.drawRect(xl, yb, barWidth, barHeight);
    label = "Unmapped";
    xl += barWidth + gap;
    g2.drawString(label, xl, yl + fontHeight);
    xl += g2.getFontMetrics().stringWidth(label) + gap * 3;

    g2.setColor(Color.GRAY);
    g2.fillRect(xl, yb, barWidth, barHeight);
    g2.setColor(Color.BLACK);
    g2.drawRect(xl, yb, barWidth, barHeight);
    label = "Unknown";
    xl += barWidth + gap;
    g2.drawString(label, xl, yl + fontHeight);

    return x1;
}

From source file:org.csml.tommo.sugar.modules.QualityHeatMapsPerTileAndBase.java

private void writeImage2HTML(HTMLReportArchive report, LaneCoordinates laneCoordinates,
        TileNumeration tileNumeration) throws IOException {
    final ResultsTableModel model = new ResultsTableModel(this, laneCoordinates, tileNumeration);

    ZipOutputStream zip = report.zipFile();
    StringBuffer b = report.htmlDocument();
    StringBuffer d = report.dataDocument();

    int imgSize = Options.getHeatmapImageSize() + 1; // add one pixel for internal grid
    int width = imgSize * model.getColumnCount() + 1; // add one pixel for left border
    int topBottomSeparator = 50;
    if (model.getTopBottomSeparatorColumn() > 0) {
        width += topBottomSeparator; // add top bottom separator
    }/*from   ww  w.  j  a v a 2s .com*/
    int height = imgSize * model.getRowCount() + 1; // add one pixel for top border
    int yOffset = 10 * model.getTileNumeration().getCycleSize(); // space for column header
    int xOffset = 20; // space for row header
    BufferedImage fullImage = new BufferedImage(width + xOffset, height + yOffset, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = (Graphics2D) fullImage.getGraphics();
    Color headerBackground = new Color(0x00, 0x00, 0x80);
    Color headerForeground = Color.WHITE;

    // Do the headers
    d.append("#Tiles: ");

    d.append("\t");
    g2.setColor(headerBackground);
    g2.fillRect(0, height, width + xOffset, yOffset);
    g2.fillRect(width, 0, xOffset, height + yOffset);
    g2.setColor(headerForeground);
    g2.setFont(g2.getFont().deriveFont(7f).deriveFont(Font.BOLD));
    drawColumnHeader(g2, model, imgSize, topBottomSeparator, height, d);

    g2.setFont(g2.getFont().deriveFont(9f).deriveFont(Font.BOLD));
    drawRowHeader(g2, model, imgSize, width, xOffset);

    long before = System.currentTimeMillis();

    for (int r = 0; r < model.getRowCount(); r++) {

        int separator = 0;
        // "header" for base position number
        for (int c = 0; c < model.getColumnCount(); c++) {
            TileBPCoordinates tileBPCoordinate = model.getCoordinateAt(r, c);
            MeanQualityMatrix matrix = getMeanQualityMatrix(tileBPCoordinate);

            if (matrix != null) {
                BufferedImage image = (BufferedImage) matrix.createBufferedImage(LinearPaintScale.PAINT_SCALE);
                g2.drawImage(image, 1 + imgSize * c + separator, 1 + imgSize * r, imgSize * (c + 1) + separator,
                        imgSize * (r + 1), 0, 0, image.getWidth(), image.getHeight(), null);
            } else {
                d.append("Missing matrix for: " + tileBPCoordinate + "\n");
            }
            if (c == model.getTopBottomSeparatorColumn()) {
                separator = topBottomSeparator;
            }
        }
    }

    g2.dispose();

    String imgFileName = "matrix_" + laneCoordinates.getFlowCell() + "_" + laneCoordinates.getLane() + ".png";
    zip.putNextEntry(new ZipEntry(report.folderName() + "/Images/" + imgFileName));
    ImageIO.write(fullImage, "png", zip);
    b.append("<img src=\"Images/" + imgFileName + "\" alt=\"full image\">\n");

    // #38: Save each mean value of tile as a matrix file e.g. CSV file format
    writeCSVFile(report, laneCoordinates, tileNumeration, model);

    long after = System.currentTimeMillis();
    d.append("Creating report time: " + (after - before));

}

From source file:edu.ku.brc.ui.dnd.SimpleGlassPane.java

@Override
protected void paintComponent(Graphics graphics) {
    Graphics2D g = (Graphics2D) graphics;

    Rectangle rect = getInternalBounds();
    int width = rect.width;
    int height = rect.height;

    if (useBGImage) {
        // Create a translucent intermediate image in which we can perform
        // the soft clipping
        GraphicsConfiguration gc = g.getDeviceConfiguration();
        if (img == null || img.getWidth() != width || img.getHeight() != height) {
            img = gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        }//from  w w w . j a v a  2 s .  c  om
        Graphics2D g2 = img.createGraphics();

        // Clear the image so all pixels have zero alpha
        g2.setComposite(AlphaComposite.Clear);
        g2.fillRect(0, 0, width, height);

        g2.setComposite(AlphaComposite.Src);
        g2.setColor(new Color(0, 0, 0, 85));
        g2.fillRect(0, 0, width, height);

        if (delegateRenderer != null) {
            delegateRenderer.render(g, g2, img);
        }

        g2.dispose();

        // Copy our intermediate image to the screen
        g.drawImage(img, rect.x, rect.y, null);
    }

    super.paintComponent(graphics);

    if (StringUtils.isNotEmpty(text)) {
        Graphics2D g2 = (Graphics2D) graphics;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(fillColor);
        g2.fillRect(margin.left, margin.top, rect.width, rect.height);

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

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

        if (yPos != null) {
            ty = yPos;
        }

        int expand = 20;
        int arc = expand * 2;

        g2.setColor(new Color(0, 0, 0, 50));

        int x = margin.left + tx - (expand / 2);
        int y = margin.top + ty - fm.getAscent() - (expand / 2);

        drawBGContainer(g2, true, x + 4, y + 6, tw + expand, th + expand, arc, arc);

        g2.setColor(new Color(255, 255, 255, 220));
        drawBGContainer(g2, true, x, y, tw + expand, th + expand, arc, arc);

        g2.setColor(Color.DARK_GRAY);
        drawBGContainer(g2, false, x, y, tw + expand, th + expand, arc, arc);

        g2.setColor(textColor == null ? Color.BLACK : textColor);
        g2.drawString(text, tx, ty);
    }
}

From source file:coolmap.canvas.datarenderer.renderer.impl.NumberToColor.java

private void updateGradient() {
    //        System.out.println("Gradient updated..");
    _gradient.reset();//from   ww  w  .jav a  2s  .c om
    for (int i = 0; i < editor.getNumPoints(); i++) {
        Color c = editor.getColorAt(i);
        float p = editor.getColorPositionAt(i);

        if (c == null || p < 0 || p > 1) {
            continue;
        }

        _gradient.addColor(c, p);
    }

    _gradientColors = _gradient.generateGradient(CImageGradient.InterType.Linear);

    int width = DEFAULT_LEGEND_WIDTH;
    int height = DEFAULT_LEGENT_HEIGHT;
    legend = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
            .getDefaultConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
    Graphics2D g = (Graphics2D) legend.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    LinearGradientPaint paint = editor.getLinearGradientPaint(0, 0, width, 0);

    g.setPaint(paint);
    g.fillRoundRect(0, 0, width, height - 12, 5, 5);

    g.setColor(UI.colorBlack2);
    g.setFont(UI.fontMono.deriveFont(10f));
    DecimalFormat format = new DecimalFormat("#.##");
    g.drawString(format.format(_minValue), 2, 23);

    String maxString = format.format(_maxValue);
    int swidth = g.getFontMetrics().stringWidth(maxString);
    g.drawString(maxString, width - 2 - swidth, 23);
    g.dispose();

    //        System.out.println("===Gradient updated===" + _gradientColors + " " + this);
}