Example usage for java.awt Graphics2D getFont

List of usage examples for java.awt Graphics2D getFont

Introduction

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

Prototype

public abstract Font getFont();

Source Link

Document

Gets the current font.

Usage

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   ww  w .ja  va2 s. c o  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:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java

private void drawTitle(Graphics2D g2) {
    final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
    final Color oldColor = g2.getColor();
    final Font oldFont = g2.getFont();

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

    final Font titleFont = oldFont.deriveFont(oldFont.getStyle() | Font.BOLD, (float) oldFont.getSize() * 1.5f);

    final int margin = 5;

    final FontMetrics titleFontMetrics = g2.getFontMetrics(titleFont);
    final FontMetrics oldFontMetrics = g2.getFontMetrics(oldFont);
    final java.text.NumberFormat numberFormat = java.text.NumberFormat.getInstance();
    numberFormat.setMaximumFractionDigits(2);
    numberFormat.setMinimumFractionDigits(2);

    final double totalInvestValue = this.investmentFlowChartJDialog.getTotalInvestValue();
    final double totalROIValue = this.investmentFlowChartJDialog.getTotalROIValue();

    final DecimalPlace decimalPlace = JStock.instance().getJStockOptions().getDecimalPlace();

    final String invest = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace,
            totalInvestValue);/*from  w  w w  .  j  a  v a2s  .  com*/
    final String roi = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, totalROIValue);
    final double gain = totalROIValue - totalInvestValue;
    final double percentage = totalInvestValue > 0.0 ? gain / totalInvestValue * 100.0 : 0.0;
    final String gain_str = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, gain);
    final String percentage_str = numberFormat.format(percentage);

    final String SELECTED = this.investmentFlowChartJDialog.getCurrentSelectedString();
    final String INVEST = GUIBundle.getString("InvestmentFlowLayerUI_Invest");
    final String RETURN = GUIBundle.getString("InvestmentFlowLayerUI_Return");
    final String GAIN = (SELECTED.length() > 0 ? SELECTED + " " : "")
            + GUIBundle.getString("InvestmentFlowLayerUI_Gain");
    final String LOSS = (SELECTED.length() > 0 ? SELECTED + " " : "")
            + GUIBundle.getString("InvestmentFlowLayerUI_Loss");

    final int string_width = oldFontMetrics.stringWidth(INVEST + ": ")
            + titleFontMetrics.stringWidth(invest + " ") + oldFontMetrics.stringWidth(RETURN + ": ")
            + titleFontMetrics.stringWidth(roi + " ")
            + oldFontMetrics.stringWidth((gain >= 0 ? GAIN : LOSS) + ": ")
            + titleFontMetrics.stringWidth(gain_str + " (" + percentage_str + "%)");

    int x = (int) (this.investmentFlowChartJDialog.getChartPanel().getWidth() - string_width) >> 1;
    final int y = margin + titleFontMetrics.getAscent();

    g2.setFont(oldFont);
    g2.drawString(INVEST + ": ", x, y);
    x += oldFontMetrics.stringWidth(INVEST + ": ");
    g2.setFont(titleFont);
    g2.drawString(invest + " ", x, y);
    x += titleFontMetrics.stringWidth(invest + " ");
    g2.setFont(oldFont);
    g2.drawString(RETURN + ": ", x, y);
    x += oldFontMetrics.stringWidth(RETURN + ": ");
    g2.setFont(titleFont);
    g2.drawString(roi + " ", x, y);
    x += titleFontMetrics.stringWidth(roi + " ");
    g2.setFont(oldFont);
    if (gain >= 0) {
        if (gain > 0) {
            if (org.yccheok.jstock.engine.Utils.isFallBelowAndRiseAboveColorReverse()) {
                g2.setColor(JStock.instance().getJStockOptions().getLowerNumericalValueForegroundColor());
            } else {
                g2.setColor(JStock.instance().getJStockOptions().getHigherNumericalValueForegroundColor());
            }
        }
        g2.drawString(GAIN + ": ", x, y);
        x += oldFontMetrics.stringWidth(GAIN + ": ");
    } else {
        if (org.yccheok.jstock.engine.Utils.isFallBelowAndRiseAboveColorReverse()) {
            g2.setColor(JStock.instance().getJStockOptions().getHigherNumericalValueForegroundColor());
        } else {
            g2.setColor(JStock.instance().getJStockOptions().getLowerNumericalValueForegroundColor());
        }
        g2.drawString(LOSS + ": ", x, y);
        x += oldFontMetrics.stringWidth(LOSS + ": ");
    }
    g2.setFont(titleFont);
    g2.drawString(gain_str + " (" + percentage_str + "%)", x, y);

    g2.setColor(oldColor);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias);
    g2.setFont(oldFont);
}

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

void drawRowHeader(Graphics2D g2, final ResultsTableModel model, int imgSize, int width, int xOffset) {
    for (int r = 0; r < model.getRowCount(); r++) {
        int bp = model.getBasePosition(r);
        if (model.getCycleID(r) == 0) {
            String s = String.valueOf(bp);
            int stringHeight = g2.getFont().getSize(); //g2.getFontMetrics().getHeight();
            int stringWidth = g2.getFontMetrics().stringWidth(s);
            g2.drawString(s, 1 + width + (xOffset - 1 - stringWidth) / 2,
                    imgSize * (r + 1) - (imgSize - stringHeight) / 2);
        }//from ww  w. j av  a 2s .com
    }
}

From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java

private void drawInformationBox(Graphics2D g2, Activities activities, Rectangle2D rect, List<String> params,
        List<String> values, String totalParam, double totalValue, Color background_color, Color border_color) {
    final Font oldFont = g2.getFont();
    final Font paramFont = oldFont;
    final FontMetrics paramFontMetrics = g2.getFontMetrics(paramFont);
    final Font valueFont = oldFont.deriveFont(oldFont.getStyle() | Font.BOLD, (float) oldFont.getSize() + 1);
    final FontMetrics valueFontMetrics = g2.getFontMetrics(valueFont);
    final Font dateFont = oldFont.deriveFont((float) oldFont.getSize() - 1);
    final FontMetrics dateFontMetrics = g2.getFontMetrics(dateFont);

    final int x = (int) rect.getX();
    final int y = (int) rect.getY();
    final int width = (int) rect.getWidth();
    final int height = (int) rect.getHeight();

    final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
    final Composite oldComposite = g2.getComposite();
    final Color oldColor = g2.getColor();

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setColor(border_color);/*from  w ww  .  ja v a  2s  .c o m*/
    g2.drawRoundRect(x - 1, y - 1, width + 1, height + 1, 15, 15);
    g2.setColor(background_color);
    g2.setComposite(Utils.makeComposite(0.75f));
    g2.fillRoundRect(x, y, width, height, 15, 15);
    g2.setComposite(oldComposite);
    g2.setColor(oldColor);

    final Date date = activities.getDate().getTime();
    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, MMMM d, yyyy");
    final String dateString = simpleDateFormat.format(date);

    final int padding = 5;

    int yy = y + padding + dateFontMetrics.getAscent();
    g2.setFont(dateFont);
    g2.setColor(COLOR_BLUE);
    g2.drawString(dateString, ((width - dateFontMetrics.stringWidth(dateString)) >> 1) + x, yy);

    int index = 0;
    final int dateInfoHeightMargin = 5;
    final int infoTotalHeightMargin = 5;
    final int paramValueHeightMargin = 0;

    yy += dateFontMetrics.getDescent() + dateInfoHeightMargin
            + Math.max(paramFontMetrics.getAscent(), valueFontMetrics.getAscent());
    for (String param : params) {
        final String value = values.get(index++);
        g2.setColor(Color.BLACK);
        g2.setFont(paramFont);
        g2.drawString(param + ":", padding + x, yy);
        g2.setFont(valueFont);
        g2.drawString(value, width - padding - valueFontMetrics.stringWidth(value) + x, yy);
        // Same as yy += valueFontMetrics.getDescent() + paramValueHeightMargin + valueFontMetrics.getAscent()
        yy += paramValueHeightMargin + Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight());
    }

    if (values.size() > 1) {
        yy -= paramValueHeightMargin;
        yy += infoTotalHeightMargin;
        if (totalValue > 0.0) {
            g2.setColor(JStockOptions.DEFAULT_HIGHER_NUMERICAL_VALUE_FOREGROUND_COLOR);
        } else if (totalValue < 0.0) {
            g2.setColor(JStockOptions.DEFAULT_LOWER_NUMERICAL_VALUE_FOREGROUND_COLOR);
        }

        g2.setFont(paramFont);
        g2.drawString(totalParam + ":", padding + x, yy);
        g2.setFont(valueFont);
        final DecimalPlace decimalPlace = JStock.instance().getJStockOptions().getDecimalPlace();
        final String totalValueStr = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace,
                totalValue);
        g2.drawString(totalValueStr, width - padding - valueFontMetrics.stringWidth(totalValueStr) + x, yy);
    }

    g2.setColor(oldColor);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias);
    g2.setFont(oldFont);
}

From source file:org.yccheok.jstock.gui.charting.ChartLayerUI.java

private void drawInformationBox(Graphics2D g2, JXLayer<? extends V> layer) {
    if (JStock.instance().getJStockOptions()
            .getYellowInformationBoxOption() == JStockOptions.YellowInformationBoxOption.Hide) {
        return;//from  ww w.  java2 s .  c o  m
    }

    final Font oldFont = g2.getFont();
    final Font paramFont = oldFont;
    final FontMetrics paramFontMetrics = g2.getFontMetrics(paramFont);
    final Font valueFont = oldFont.deriveFont(oldFont.getStyle() | Font.BOLD, (float) oldFont.getSize() + 1);
    final FontMetrics valueFontMetrics = g2.getFontMetrics(valueFont);
    final Font dateFont = oldFont.deriveFont((float) oldFont.getSize() - 1);
    final FontMetrics dateFontMetrics = g2.getFontMetrics(dateFont);

    final List<ChartData> chartDatas = this.chartJDialog.getChartDatas();
    List<String> values = new ArrayList<String>();
    final ChartData chartData = chartDatas.get(this.mainTraceInfo.getDataIndex());

    // Number formats are generally not synchronized. It is recommended to create separate format instances for each thread. 
    // If multiple threads access a format concurrently, it must be synchronized externally.
    // http://stackoverflow.com/questions/2213410/usage-of-decimalformat-for-the-following-case
    final DecimalFormat integerFormat = new DecimalFormat("###,###");

    // It is common to use OHLC for chat, instead of using PrevPrice.        
    values.add(org.yccheok.jstock.gui.Utils.stockPriceDecimalFormat(chartData.openPrice));
    values.add(org.yccheok.jstock.gui.Utils.stockPriceDecimalFormat(chartData.highPrice));
    values.add(org.yccheok.jstock.gui.Utils.stockPriceDecimalFormat(chartData.lowPrice));
    values.add(org.yccheok.jstock.gui.Utils.stockPriceDecimalFormat(chartData.lastPrice));
    values.add(integerFormat.format(chartData.volume));

    final List<String> indicatorParams = new ArrayList<String>();
    final List<String> indicatorValues = new ArrayList<String>();
    final DecimalFormat decimalFormat = new DecimalFormat("0.00");
    for (TraceInfo indicatorTraceInfo : this.indicatorTraceInfos) {
        final int plotIndex = indicatorTraceInfo.getPlotIndex();
        final int seriesIndex = indicatorTraceInfo.getSeriesIndex();
        final int dataIndex = indicatorTraceInfo.getDataIndex();
        final String name = this.getLegendName(plotIndex, seriesIndex);
        final Number value = this.getValue(plotIndex, seriesIndex, dataIndex);
        if (name == null || value == null) {
            continue;
        }
        indicatorParams.add(name);
        indicatorValues.add(decimalFormat.format(value));
    }

    assert (values.size() == params.size());
    int index = 0;
    final int paramValueWidthMargin = 10;
    final int paramValueHeightMargin = 0;
    // Slightly larger than dateInfoHeightMargin, as font for indicator is
    // larger than date's.
    final int infoIndicatorHeightMargin = 8;
    int maxInfoWidth = -1;
    // paramFontMetrics will always "smaller" than valueFontMetrics.
    int totalInfoHeight = Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight()) * values.size()
            + paramValueHeightMargin * (values.size() - 1);
    for (String param : params) {
        final String value = values.get(index++);
        final int paramStringWidth = paramFontMetrics.stringWidth(param + ":") + paramValueWidthMargin
                + valueFontMetrics.stringWidth(value);
        if (maxInfoWidth < paramStringWidth) {
            maxInfoWidth = paramStringWidth;
        }
    }

    if (indicatorValues.size() > 0) {
        totalInfoHeight += infoIndicatorHeightMargin;
        totalInfoHeight += Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight())
                * indicatorValues.size() + paramValueHeightMargin * (indicatorValues.size() - 1);
        index = 0;
        for (String indicatorParam : indicatorParams) {
            final String indicatorValue = indicatorValues.get(index++);
            final int paramStringWidth = paramFontMetrics.stringWidth(indicatorParam + ":")
                    + paramValueWidthMargin + valueFontMetrics.stringWidth(indicatorValue);
            if (maxInfoWidth < paramStringWidth) {
                maxInfoWidth = paramStringWidth;
            }
        }
    }

    final Date date = new Date(chartData.timestamp);

    // Date formats are not synchronized. It is recommended to create separate format instances for each thread.
    // If multiple threads access a format concurrently, it must be synchronized externally.
    final SimpleDateFormat simpleDateFormat = this.simpleDataFormatThreadLocal.get();
    final String dateString = simpleDateFormat.format(date);
    final int dateStringWidth = dateFontMetrics.stringWidth(dateString);
    final int dateStringHeight = dateFontMetrics.getHeight();
    // We want to avoid information box from keep changing its width while
    // user moves along the mouse. This will prevent user from feeling,
    // information box is flickering, which is uncomfortable to user's eye.
    final int maxStringWidth = Math.max(dateFontMetrics.stringWidth(longDateString),
            Math.max(this.maxWidth, Math.max(dateStringWidth, maxInfoWidth)));
    if (maxStringWidth > this.maxWidth) {
        this.maxWidth = maxStringWidth;
    }
    final int dateInfoHeightMargin = 5;
    final int maxStringHeight = dateStringHeight + dateInfoHeightMargin + totalInfoHeight;

    final int padding = 5;
    final int boxPointMargin = 8;
    final int width = maxStringWidth + (padding << 1);
    final int height = maxStringHeight + (padding << 1);

    /* Get Border Rect Information. */
    /*
    fillRect(1, 1, 1, 1);   // O is rect pixel
            
    xxx
    xOx
    xxx
            
    drawRect(0, 0, 2, 2);   // O is rect pixel
            
    OOO
    OxO
    OOO
     */
    final int borderWidth = width + 2;
    final int borderHeight = height + 2;
    // On left side of the ball.
    final double suggestedBorderX = this.mainTraceInfo.getPoint().getX() - borderWidth - boxPointMargin;
    final double suggestedBorderY = this.mainTraceInfo.getPoint().getY() - (borderHeight >> 1);
    double bestBorderX = 0;
    double bestBorderY = 0;
    if (JStock.instance().getJStockOptions()
            .getYellowInformationBoxOption() == JStockOptions.YellowInformationBoxOption.Stay) {
        if (this.mainTraceInfo.getPoint()
                .getX() > ((int) (this.mainDrawArea.getX() + this.mainDrawArea.getWidth() + 0.5) >> 1)) {
            bestBorderX = this.mainDrawArea.getX();
            bestBorderY = this.mainDrawArea.getY();
        } else {
            bestBorderX = this.mainDrawArea.getX() + this.mainDrawArea.getWidth() - borderWidth;
            bestBorderY = this.mainDrawArea.getY();
        }
    } else {
        assert (JStock.instance().getJStockOptions()
                .getYellowInformationBoxOption() == JStockOptions.YellowInformationBoxOption.Follow);
        bestBorderX = suggestedBorderX > this.mainDrawArea.getX()
                ? (suggestedBorderX + borderWidth) < (this.mainDrawArea.getX() + this.mainDrawArea.getWidth())
                        ? suggestedBorderX
                        : this.mainDrawArea.getX() + this.mainDrawArea.getWidth() - borderWidth - boxPointMargin
                : this.mainTraceInfo.getPoint().getX() + boxPointMargin;
        bestBorderY = suggestedBorderY > this.mainDrawArea.getY()
                ? (suggestedBorderY + borderHeight) < (this.mainDrawArea.getY() + this.mainDrawArea.getHeight())
                        ? suggestedBorderY
                        : this.mainDrawArea.getY() + this.mainDrawArea.getHeight() - borderHeight
                                - boxPointMargin
                : this.mainDrawArea.getY() + boxPointMargin;
    }

    final double x = bestBorderX + 1;
    final double y = bestBorderY + 1;

    final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
    final Composite oldComposite = g2.getComposite();
    final Color oldColor = g2.getColor();

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setColor(COLOR_BORDER);
    g2.drawRoundRect((int) (bestBorderX + 0.5), (int) (bestBorderY + 0.5), borderWidth - 1, borderHeight - 1,
            15, 15);
    g2.setColor(COLOR_BACKGROUND);
    g2.setComposite(Utils.makeComposite(0.75f));
    g2.fillRoundRect((int) (x + 0.5), (int) (y + 0.5), width, height, 15, 15);
    g2.setComposite(oldComposite);
    g2.setColor(oldColor);

    int yy = (int) (y + padding + dateFontMetrics.getAscent() + 0.5);
    g2.setFont(dateFont);
    g2.setColor(COLOR_BLUE);
    g2.drawString(dateString, (int) (((width - dateFontMetrics.stringWidth(dateString)) >> 1) + x + 0.5), yy);

    index = 0;
    yy += dateFontMetrics.getDescent() + dateInfoHeightMargin + valueFontMetrics.getAscent();
    final String CLOSE_STR = GUIBundle.getString("StockHistory_Close");
    for (String param : params) {
        final String value = values.get(index++);
        g2.setColor(Color.BLACK);
        if (param.equals(CLOSE_STR)) {
            // It is common to use OHLC for chat, instead of using PrevPrice.
            final double changePrice = chartData.lastPrice - chartData.openPrice;
            if (changePrice > 0.0) {
                g2.setColor(JStockOptions.DEFAULT_HIGHER_NUMERICAL_VALUE_FOREGROUND_COLOR);
            } else if (changePrice < 0.0) {
                g2.setColor(JStockOptions.DEFAULT_LOWER_NUMERICAL_VALUE_FOREGROUND_COLOR);
            }
        }
        g2.setFont(paramFont);
        g2.drawString(param + ":", (int) (padding + x + 0.5), yy);
        g2.setFont(valueFont);
        g2.drawString(value, (int) (width - padding - valueFontMetrics.stringWidth(value) + x + 0.5), yy);
        // Same as yy += valueFontMetrics.getDescent() + paramValueHeightMargin + valueFontMetrics.getAscent()
        yy += paramValueHeightMargin + valueFontMetrics.getHeight();
    }

    g2.setColor(Color.BLACK);
    yy -= paramValueHeightMargin;
    yy += infoIndicatorHeightMargin;

    index = 0;
    for (String indicatorParam : indicatorParams) {
        final String indicatorValue = indicatorValues.get(index++);
        g2.setFont(paramFont);
        g2.drawString(indicatorParam + ":", (int) (padding + x + 0.5), yy);
        g2.setFont(valueFont);
        g2.drawString(indicatorValue,
                (int) (width - padding - valueFontMetrics.stringWidth(indicatorValue) + x + 0.5), yy);
        // Same as yy += valueFontMetrics.getDescent() + paramValueHeightMargin + valueFontMetrics.getAscent()
        yy += paramValueHeightMargin + valueFontMetrics.getHeight();
    }

    g2.setColor(oldColor);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias);
    g2.setFont(oldFont);
}

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./*www  .j  av  a 2s . c  o m*/
 *
 * @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:org.eurocarbdb.application.glycoworkbench.plugin.reporting.AnnotationReportCanvas.java

protected void paintAnnotations(Graphics2D g2d) {

    DecimalFormat mz_df = new DecimalFormat("0.0");

    // set font//from ww  w. j  a va  2  s . c o m
    Font old_font = g2d.getFont();
    Font new_font = new Font(theOptions.ANNOTATION_MZ_FONT, Font.PLAIN, theOptions.ANNOTATION_MZ_SIZE);

    // compute bboxes
    PositionManager pman = new PositionManager();
    BBoxManager bbman = new BBoxManager();
    computeRectangles(pman, bbman);

    // compute connections
    computeConnections();

    // paint connections
    for (AnnotationObject a : theDocument.getAnnotations()) {
        boolean selected = !is_printing && selections.contains(a);

        // paint arrow        
        Polygon connection = connections.get(a);
        if (connection != null) {
            g2d.setColor(theOptions.CONNECTION_LINES_COLOR);
            g2d.setStroke((selected) ? new BasicStroke((float) (1. + theOptions.ANNOTATION_LINE_WIDTH))
                    : new BasicStroke((float) theOptions.ANNOTATION_LINE_WIDTH));
            g2d.draw(connection);
            g2d.setStroke(new BasicStroke(1));
        }

        // paint control point       
        if (selected) {
            g2d.setColor(Color.black);
            Point2D cp = connections_cp.get(a);
            if (cp != null) {
                int s = (int) (2 + theOptions.ANNOTATION_LINE_WIDTH);
                g2d.fill(new Rectangle((int) cp.getX() - s, (int) cp.getY() - s, 2 * s, 2 * s));
            }
        }
    }

    // paint glycans
    for (AnnotationObject a : theDocument.getAnnotations()) {
        boolean highlighted = a.isHighlighted();
        boolean selected = !is_printing && selections.contains(a);

        // set scale
        theGlycanRenderer.getGraphicOptions().setScale(theOptions.SCALE_GLYCANS * theDocument.getScale(a));

        // paint highlighted region
        if (highlighted) {
            Rectangle c_bbox = rectangles_complete.get(a);

            g2d.setColor(theOptions.HIGHLIGHTED_COLOR);
            g2d.setXORMode(Color.white);
            g2d.fill(c_bbox);
            g2d.setPaintMode();

            g2d.setColor(Color.black);
            g2d.draw(c_bbox);
        }

        // paint glycan
        for (Glycan s : a.getStructures())
            theGlycanRenderer.paint(g2d, s, null, null, false, false, pman, bbman);

        // paint MZ text
        g2d.setFont(new_font);
        g2d.setColor(theOptions.MASS_TEXT_COLOR);
        String mz_text = mz_df.format(a.getPeakPoint().getX());
        Rectangle mz_bbox = rectangles_text.get(a);
        g2d.drawString(mz_text, mz_bbox.x, mz_bbox.y + mz_bbox.height);

        // paint selection        
        if (selected) {
            // paint rectangle
            Rectangle c_bbox = rectangles_complete.get(a);

            g2d.setStroke(new BasicStroke(highlighted ? 2 : 1));
            g2d.setColor(Color.black);

            g2d.draw(c_bbox);

            g2d.setStroke(new BasicStroke(1));

            // paint resize points        
            Polygon p1 = new Polygon();
            int cx1 = right(c_bbox);
            int cy1 = top(c_bbox);
            p1.addPoint(cx1, cy1);
            p1.addPoint(cx1 - 2 * theOptions.ANNOTATION_MARGIN / 3, cy1);
            p1.addPoint(cx1, cy1 + 2 * theOptions.ANNOTATION_MARGIN / 3);
            g2d.fill(p1);

            Polygon p2 = new Polygon();
            int cx2 = left(c_bbox);
            int cy2 = top(c_bbox);
            p2.addPoint(cx2, cy2);
            p2.addPoint(cx2 + 2 * theOptions.ANNOTATION_MARGIN / 3, cy2);
            p2.addPoint(cx2, cy2 + 2 * theOptions.ANNOTATION_MARGIN / 3);
            g2d.fill(p2);
        }
    }

    g2d.setFont(old_font);
}

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
    }/*  ww w .  j a v a 2  s .  co m*/
    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:savant.view.swing.GraphPane.java

/**
 * Draw an informational message on top of this GraphPane.
 *
 * @param g2 the graphics to be rendered
 * @param message text of the message to be displayed
 *//*w w  w  . ja  va 2s . co m*/
private void drawMessage(Graphics2D g2, String message) {

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    Font font = g2.getFont();
    Font subFont = font;

    int h = getSize().height / 3;
    int w = getWidth();

    if (w > 500) {
        font = font.deriveFont(Font.PLAIN, 36);
        subFont = subFont.deriveFont(Font.PLAIN, 18);
    } else if (w > 150) {
        font = font.deriveFont(Font.PLAIN, 24);
        subFont = subFont.deriveFont(Font.PLAIN, 12);
    } else {
        font = font.deriveFont(Font.PLAIN, 12);
        subFont = subFont.deriveFont(Font.PLAIN, 8);
    }

    int returnPos = message.indexOf('\n');
    g2.setColor(ColourSettings.getColor(ColourKey.GRAPH_PANE_MESSAGE));
    if (returnPos > 0) {
        drawMessageHelper(g2, message.substring(0, returnPos), font, w, h, -(subFont.getSize() / 2));
        drawMessageHelper(g2, message.substring(returnPos + 1), subFont, w, h,
                font.getSize() - (subFont.getSize() / 2));
    } else {
        drawMessageHelper(g2, message, font, w, h, 0);
    }
}

From source file:net.sf.mzmine.modules.visualization.metamsecorrelate.visual.pseudospectra.PseudoSpectraRenderer.java

@Override
protected void drawItemLabel(Graphics2D g2, XYDataset dataset, int series, int item, XYPlot plot,
        XYItemLabelGenerator generator, Rectangle2D bar, boolean negative) {
    //super.drawItemLabel(g2, dataset, series, item, plot, generator, bar, negative);  

    if (generator != null) {
        String label = generator.generateLabel(dataset, series, item);

        if (label != null) {
            Font labelFont = getItemLabelFont(series, item);
            Paint paint = getItemLabelPaint(series, item);
            g2.setFont(labelFont);//from w  ww  .j  a v a 2  s . c o  m
            g2.setPaint(paint);

            // get the label position..
            ItemLabelPosition position;
            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());

            // split by \n
            String symbol = "\n";
            String[] splitted = label.split(symbol);

            if (splitted.length > 1) {
                FontRenderContext frc = g2.getFontRenderContext();
                GlyphVector gv = g2.getFont().createGlyphVector(frc, "Fg,");
                int height = 4 + (int) gv.getPixelBounds(null, 0, 0).getHeight();
                // draw more than one row
                for (int i = 0; i < splitted.length; i++) {
                    int offset = -height * (splitted.length - i - 1);
                    TextUtilities.drawRotatedString(splitted[i], g2, (float) anchorPoint.getX(),
                            (float) anchorPoint.getY() + offset, position.getTextAnchor(), position.getAngle(),
                            position.getRotationAnchor());
                }
            } else {
                // one row 
                TextUtilities.drawRotatedString(label, g2, (float) anchorPoint.getX(),
                        (float) anchorPoint.getY(), position.getTextAnchor(), position.getAngle(),
                        position.getRotationAnchor());
            }
        }
    }

}