Example usage for java.awt Graphics2D fillRect

List of usage examples for java.awt Graphics2D fillRect

Introduction

In this page you can find the example usage for java.awt Graphics2D 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:edu.harvard.iq.dvn.core.web.ExploreDataPage.java

private BufferedImage getCompositeImage(BufferedImage image) throws FontFormatException, IOException {
    Integer heightAdjustment = new Integer(0);
    if (this.heightInt == 1) {
        heightAdjustment = 40;/*  w w w  . ja v  a  2  s .c  o m*/
    }
    if (this.heightInt == 3) {
        heightAdjustment = -100;
    }

    BufferedImage yAxisImage = new BufferedImage(100, 500, BufferedImage.TYPE_INT_ARGB);
    BufferedImage combinedImage = new BufferedImage(776, 575 + heightAdjustment, BufferedImage.TYPE_INT_ARGB);

    if (graphTitle.trim().isEmpty()) {
        graphTitle = " ";
    }

    File retFile = generateImageString("16", "620x", "South", "0", graphTitle);
    BufferedImage titleImage = ImageIO.read(retFile);
    if (!FileUtil.keepTempFiles("core.web.ExploreDataPage")) {
        if (retFile != null && retFile.exists()) {
            retFile.delete();
        }
    }

    String source = "";

    if (!sourceString.trim().isEmpty()) {
        source = sourceString;
    }

    if (source.trim().isEmpty()) {
        source = " ";
    }
    retFile = generateImageString("14", "676x", "NorthWest", "0", source);
    BufferedImage sourceImage = ImageIO.read(retFile);
    if (!FileUtil.keepTempFiles("core.web.ExploreDataPage")) {
        if (retFile != null && retFile.exists()) {
            retFile.delete();
        }
    }

    if (yAxisLabel.trim().isEmpty()) {
        yAxisLabel = " ";
    }
    retFile = generateImageString("14", new Integer(350 + heightAdjustment) + "x", "South", "-90", yAxisLabel);
    BufferedImage yAxisVertImage = ImageIO.read(retFile);
    if (!FileUtil.keepTempFiles("core.web.ExploreDataPage")) {
        if (retFile != null && retFile.exists()) {
            retFile.delete();
        }
    }

    Graphics2D yag2 = yAxisImage.createGraphics();
    Graphics2D cig2 = combinedImage.createGraphics();
    Graphics2D sig2 = sourceImage.createGraphics();

    cig2.setColor(Color.WHITE);
    yag2.setColor(Color.WHITE);
    yag2.fillRect(0, 0, 676, 500);
    cig2.fillRect(0, 0, 776, 550);

    cig2.drawImage(yAxisImage, 0, 0, null);
    cig2.drawImage(yAxisVertImage, 15, 50, null);
    cig2.drawImage(image, 50, 50, null);
    cig2.drawImage(titleImage, 85, 15, null);
    cig2.drawImage(sourceImage, 45, 475 + heightAdjustment, null);

    yag2.dispose();
    sig2.dispose();
    cig2.dispose();

    return combinedImage;
}

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

public void fillRegion(Graphics2D g, boolean chessboard) {
    if (!resolved) {
        fillcolor = getColor(mainClass.classIndex);
        Color c = repairColor(fillcolor);
        g.setColor(c);/*from  w  w w . j  a va 2s.  com*/
        if (segments.isEmpty()) {
            return;
        }
        g.fillPolygon(this);
    } else {
        if (chessboard) {
            if (polygons == null) { // calculate polygons
                polygons = new ArrayList<Polygon>();

                Rectangle2D rect = getBounds2D();
                double w = rect.getWidth();

                double h = rect.getHeight();

                if (h > 200 || w > 200) {
                    Logger.getLogger("at.tuwien.ifs.somtoolbox").info("ERROR: h>200 || w>200");
                    return;
                }

                int x = (int) rect.getX();
                int y = (int) rect.getY();

                int xSteps = (int) (w / (int) Grid.SIZE);
                int ySteps = (int) (h / (int) Grid.SIZE);
                // int n = classes.size();
                for (int i = 0; i < xSteps; i++) {
                    for (int j = 0; j < ySteps; j++) {
                        Polygon p = new Polygon();
                        p.addPoint((int) (x + i * Grid.SIZE), (int) (y + j * Grid.SIZE));
                        p.addPoint((int) (x + i * Grid.SIZE + Grid.SIZE), (int) (y + j * Grid.SIZE));
                        p.addPoint((int) (x + i * Grid.SIZE + Grid.SIZE),
                                (int) (y + Grid.SIZE + j * Grid.SIZE));
                        p.addPoint((int) (x + i * Grid.SIZE), (int) (y + Grid.SIZE + j * Grid.SIZE));
                        if (!this.contains(p.getBounds())) {
                            continue;
                        }
                        SOMClass clss = indexGenerator.getNextIndex();
                        g.setColor(getColor(clss.classIndex));
                        g.fillPolygon(p);
                        polygons.add(p);
                    }
                }
            } else { // use pre-calculated polygons
                for (int i = 0; i < polygons.size(); i++) {
                    SOMClass clss = indexGenerator.getNextIndex();
                    g.setColor(getColor(clss.classIndex));
                    Polygon p = polygons.get(i);
                    g.fillPolygon(p);
                }
            }
        } else {
            for (int i = 0; i < grids.size(); i++) {
                Grid grid = grids.get(i);
                if (grid.clss == null) {
                    continue;
                }
                g.setColor(getColor(grid.clss.classIndex));
                g.fillRect((int) grid.topLeft.coord(0), (int) grid.topLeft.coord(1), (int) Grid.SIZE,
                        (int) Grid.SIZE);
            }
        }
    }
}

From source file:com.aerohive.nms.web.config.lbs.services.HmFolderServiceImpl.java

private void createNodeImage(long id, Map<Long, Integer> channelMap, Map<Long, Integer> colorMap, int x, int y,
        Graphics2D g2) {
    Integer channel = channelMap.get(id);
    Integer colorIndex = colorMap.get(id);
    int radius = 11;
    if (channel == null || channel == 0 || colorIndex == null || colorIndex > startChannelColors.length - 1) {
        g2.setColor(new Color(180, 180, 180));
        g2.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
        return;/*from  ww w . j  a  v  a 2 s .c o m*/
    }
    g2.setColor(startChannelColors[colorIndex]);
    g2.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
    int dy = 6, w = 21;
    g2.fillRect(x, y - dy, w, dy + dy);
    dy = 5;
    g2.setColor(new Color(255, 255, 255));
    g2.fillRect(x + 1, y - dy, w - 2, dy + dy);
    g2.setColor(new Color(0, 51, 102));
    int chx = x + 2;
    if (channel < 100) {
        chx += 3;
    }
    if (channel < 10) {
        chx += 3;
    }
    g2.drawString("" + channel, chx, y + 4);
}

From source file:SWT2D.java

private void run() {
    // Create top level shell
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Java 2D Example");
    // GridLayout for canvas and button
    shell.setLayout(new GridLayout());
    // Create container for AWT canvas
    final Composite canvasComp = new Composite(shell, SWT.EMBEDDED);
    // Set preferred size
    GridData data = new GridData();
    data.widthHint = 600;/*w ww  .  j  a  v  a  2 s . co  m*/
    data.heightHint = 500;
    canvasComp.setLayoutData(data);
    // Create AWT Frame for Canvas
    java.awt.Frame canvasFrame = SWT_AWT.new_Frame(canvasComp);
    // Create Canvas and add it to the Frame
    final java.awt.Canvas canvas = new java.awt.Canvas();
    canvasFrame.add(canvas);
    // Get graphical context and cast to Java2D
    final java.awt.Graphics2D g2d = (java.awt.Graphics2D) canvas.getGraphics();
    // Enable antialiasing
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    // Remember initial transform
    final java.awt.geom.AffineTransform origTransform = g2d.getTransform();
    // Create Clear button and position it
    Button clearButton = new Button(shell, SWT.PUSH);
    clearButton.setText("Clear");
    data = new GridData();
    data.horizontalAlignment = GridData.CENTER;
    clearButton.setLayoutData(data);
    // Event processing for Clear button
    clearButton.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            // Delete word list and redraw canvas
            wordList.clear();
            canvasComp.redraw();
        }
    });
    // Process canvas mouse clicks
    canvas.addMouseListener(new java.awt.event.MouseListener() {
        public void mouseClicked(java.awt.event.MouseEvent e) {
        }

        public void mouseEntered(java.awt.event.MouseEvent e) {
        }

        public void mouseExited(java.awt.event.MouseEvent e) {
        }

        public void mousePressed(java.awt.event.MouseEvent e) {
            // Manage pop-up editor
            display.syncExec(new Runnable() {
                public void run() {
                    if (eShell == null) {
                        // Create new Shell: non-modal!
                        eShell = new Shell(shell, SWT.NO_TRIM | SWT.MODELESS);
                        eShell.setLayout(new FillLayout());
                        // Text input field
                        eText = new Text(eShell, SWT.BORDER);
                        eText.setText("Text rotation in the SWT?");
                        eShell.pack();
                        // Set position (Display coordinates)
                        java.awt.Rectangle bounds = canvas.getBounds();
                        org.eclipse.swt.graphics.Point pos = canvasComp.toDisplay(bounds.width / 2,
                                bounds.height / 2);
                        Point size = eShell.getSize();
                        eShell.setBounds(pos.x, pos.y, size.x, size.y);
                        // Open Shell
                        eShell.open();
                    } else if (!eShell.isVisible()) {
                        // Editor versteckt, sichtbar machen
                        eShell.setVisible(true);
                    } else {
                        // Editor is visible - get text
                        String t = eText.getText();
                        // set editor invisible
                        eShell.setVisible(false);
                        // Add text to list and redraw canvas
                        wordList.add(t);
                        canvasComp.redraw();
                    }
                }
            });
        }

        public void mouseReleased(java.awt.event.MouseEvent e) {
        }
    });
    // Redraw the canvas
    canvasComp.addPaintListener(new PaintListener() {
        public void paintControl(PaintEvent e) {
            // Pass the redraw task to AWT event queue
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    // Compute canvas center
                    java.awt.Rectangle bounds = canvas.getBounds();
                    int originX = bounds.width / 2;
                    int originY = bounds.height / 2;
                    // Reset canvas
                    g2d.setTransform(origTransform);
                    g2d.setColor(java.awt.Color.WHITE);
                    g2d.fillRect(0, 0, bounds.width, bounds.height);
                    // Set font
                    g2d.setFont(new java.awt.Font("Myriad", java.awt.Font.PLAIN, 32));
                    double angle = 0d;
                    // Prepare star shape
                    double increment = Math.toRadians(30);
                    Iterator iter = wordList.iterator();
                    while (iter.hasNext()) {
                        // Determine text colors in RGB color cycle
                        float red = (float) (0.5 + 0.5 * Math.sin(angle));
                        float green = (float) (0.5 + 0.5 * Math.sin(angle + Math.toRadians(120)));
                        float blue = (float) (0.5 + 0.5 * Math.sin(angle + Math.toRadians(240)));
                        g2d.setColor(new java.awt.Color(red, green, blue));
                        // Redraw text
                        String text = (String) iter.next();
                        g2d.drawString(text, originX + 50, originY);
                        // Rotate for next text output
                        g2d.rotate(increment, originX, originY);
                        angle += increment;
                    }
                }
            });
        }
    });
    // Finish shell and open it
    shell.pack();
    shell.open();
    // SWT event processing
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

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

/**
 * Draws bars representing the total number of sequences for each dataset
 * and the assigned subsets for each species/reference genome to which
 * these have been aligned./*w w w .  j  av a2  s  .c om*/
 *
 * @param g2
 * @param offset
 * @param height
 * @param separation
 * @param x0
 * @param x1
 * @param maxSequenceCount
 * @param multiGenomeAlignmentSummaries
 */
private void drawAlignmentBars(Graphics2D g2, int offset, int height, int separation, int x0, int x1,
        long maxSequenceCount, Collection<MultiGenomeAlignmentSummary> multiGenomeAlignmentSummaries) {
    AlignmentSummaryComparator alignmentSummaryComparator = new AlignmentSummaryComparator();

    g2.setColor(Color.BLACK);

    int y = offset;
    for (MultiGenomeAlignmentSummary multiGenomeAlignmentSummary : multiGenomeAlignmentSummaries) {
        int sampledCount = multiGenomeAlignmentSummary.getSampledCount();
        long sequenceCount = multiGenomeAlignmentSummary.getSequenceCount();
        log.debug(multiGenomeAlignmentSummary.getDatasetId() + " " + sequenceCount);

        Set<String> species = new HashSet<String>();
        Set<String> controls = new HashSet<String>();
        for (OrderedProperties sampleProperties : multiGenomeAlignmentSummary.getSampleProperties()) {
            String value = sampleProperties.getProperty(SPECIES_PROPERTY_NAMES);
            if (value != null)
                species.add(value);
            String control = sampleProperties.getProperty(CONTROL_PROPERTY_NAMES);
            if ("Yes".equals(control))
                controls.add(value);
        }

        double width = (double) sequenceCount * (x1 - x0) / maxSequenceCount;

        int total = 0;
        int x = x0;

        // iterate over alignments for various reference genomes drawing bar for each
        List<AlignmentSummary> alignmentSummaryList = Arrays
                .asList(multiGenomeAlignmentSummary.getAlignmentSummaries());
        Collections.sort(alignmentSummaryList, alignmentSummaryComparator);
        for (AlignmentSummary alignmentSummary : alignmentSummaryList) {
            total += alignmentSummary.getAssignedCount();
            int w = (int) (width * total / sampledCount) - x + x0;

            String referenceGenomeId = alignmentSummary.getReferenceGenomeId();
            String referenceGenomeName = getReferenceGenomeName(referenceGenomeId);
            Color color = Color.RED;
            if (controls.contains(referenceGenomeName)) {
                color = Color.ORANGE;
            } else if (species.contains(referenceGenomeName)) {
                color = Color.GREEN;
            } else if (species.isEmpty() || species.contains("Other") || species.contains("other")) {
                color = Color.GRAY;
            }

            float alpha = MAX_ALPHA - (MAX_ALPHA - MIN_ALPHA)
                    * (alignmentSummary.getAssignedErrorRate() - MIN_ERROR) / (MAX_ERROR - MIN_ERROR);
            alpha = Math.max(alpha, MIN_ALPHA);
            alpha = Math.min(alpha, MAX_ALPHA);
            if (alignmentSummary.getAssignedCount() >= 100)
                log.debug(alignmentSummary.getReferenceGenomeId() + "\t" + alignmentSummary.getAssignedCount()
                        + "\t" + alignmentSummary.getErrorRate() * 100.0f + "\t" + alpha);

            Composite origComposite = g2.getComposite();
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
            g2.setColor(color);
            g2.fillRect(x, y, w, height);
            g2.setComposite(origComposite);

            g2.setColor(Color.BLACK);
            g2.drawRect(x, y, w, height);
            x += w;
        }

        // bar for all sequences
        g2.drawRect(x0, y, (int) width, height);

        // bar for adapter sequences
        int adapterCount = multiGenomeAlignmentSummary.getAdapterCount();
        log.debug("Adapter count: " + adapterCount + " / " + sampledCount);
        int ya = y + height + height / 5;
        double wa = width * adapterCount / sampledCount;
        if (wa > 2) {
            int ha = height / 3;
            g2.setColor(ADAPTER_COLOR);
            g2.fillRect(x0, ya, (int) wa, ha);
            g2.setColor(Color.BLACK);
            g2.drawRect(x0, ya, (int) wa, ha);
        }

        y += separation;
    }
}

From source file:org.forester.archaeopteryx.TreePanel.java

final private void paintFoundNode(final int x, final int y, final Graphics2D g) {
    g.setColor(getTreeColorSet().getFoundColor());
    g.fillRect(x - TreePanel.HALF_BOX_SIZE, y - TreePanel.HALF_BOX_SIZE, TreePanel.BOX_SIZE,
            TreePanel.BOX_SIZE);//from  w w w  .ja  v  a 2 s  .co m
}

From source file:org.forester.archaeopteryx.TreePanel.java

final void paintPhylogeny(final Graphics2D g, final boolean to_pdf, final boolean to_graphics_file,
        final int graphics_file_width, final int graphics_file_height, final int graphics_file_x,
        final int graphics_file_y) {
    /* GUILHEM_BEG */
    _query_sequence = _control_panel.getSelectedQuerySequence();
    /* GUILHEM_END */
    // Color the background
    if (!to_pdf) {
        final Rectangle r = getVisibleRect();
        if (!getOptions().isBackgroundColorGradient() || getOptions().isPrintBlackAndWhite()) {
            g.setColor(getTreeColorSet().getBackgroundColor());
            if (!to_graphics_file) {
                g.fill(r);//  w w  w.j  a v a 2s . c  o m
            } else {
                if (getOptions().isPrintBlackAndWhite()) {
                    g.setColor(Color.WHITE);
                }
                g.fillRect(graphics_file_x, graphics_file_y, graphics_file_width, graphics_file_height);
            }
        } else {
            if (!to_graphics_file) {
                g.setPaint(new GradientPaint(r.x, r.y, getTreeColorSet().getBackgroundColor(), r.x,
                        r.y + r.height, getTreeColorSet().getBackgroundColorGradientBottom()));
                g.fill(r);
            } else {
                g.setPaint(new GradientPaint(graphics_file_x, graphics_file_y,
                        getTreeColorSet().getBackgroundColor(), graphics_file_x,
                        graphics_file_y + graphics_file_height,
                        getTreeColorSet().getBackgroundColorGradientBottom()));
                g.fillRect(graphics_file_x, graphics_file_y, graphics_file_width, graphics_file_height);
            }
        }
        g.setStroke(new BasicStroke(1));
    } else {
        g.setStroke(new BasicStroke(getOptions().getPrintLineWidth()));
    }
    if ((getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.UNROOTED)
            && (getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR)) {
        _external_node_index = 0;
        // Position starting X of tree
        if (!_phylogeny.isRooted()) {
            _phylogeny.getRoot().setXcoord(TreePanel.MOVE);
        } else if ((_phylogeny.getRoot().getDistanceToParent() > 0.0) && getControlPanel().isDrawPhylogram()) {
            _phylogeny.getRoot().setXcoord((float) (TreePanel.MOVE
                    + (_phylogeny.getRoot().getDistanceToParent() * getXcorrectionFactor())));
        } else {
            _phylogeny.getRoot().setXcoord(TreePanel.MOVE + getXdistance());
        }
        // Position starting Y of tree
        _phylogeny.getRoot().setYcoord(
                (getYdistance() * _phylogeny.getRoot().getNumberOfExternalNodes()) + (TreePanel.MOVE / 2.0f));
        final int dynamic_hiding_factor = (int) (getTreeFontSet()._fm_large.getHeight()
                / (1.5 * getYdistance()));
        if (getControlPanel().isDynamicallyHideData()) {
            if (dynamic_hiding_factor > 1) {
                getControlPanel().setDynamicHidingIsOn(true);
            } else {
                getControlPanel().setDynamicHidingIsOn(false);
            }
        }
        final PhylogenyNodeIterator it;
        for (it = _phylogeny.iteratorPreorder(); it.hasNext();) {
            paintNodeRectangular(g, it.next(), to_pdf,
                    getControlPanel().isDynamicallyHideData() && (dynamic_hiding_factor > 1),
                    dynamic_hiding_factor, to_graphics_file);
        }
        if (getOptions().isShowScale()) {
            if (!(to_graphics_file || to_pdf)) {
                paintScale(g, getVisibleRect().x, getVisibleRect().y + getVisibleRect().height, to_pdf,
                        to_graphics_file);
            } else {
                paintScale(g, graphics_file_x, graphics_file_y + graphics_file_height, to_pdf,
                        to_graphics_file);
            }
        }
        if (getOptions().isShowOverview() && isOvOn() && !to_graphics_file && !to_pdf) {
            paintPhylogenyLite(g);
        }
    } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED) {
        if (getControlPanel().getDynamicallyHideData() != null) {
            getControlPanel().setDynamicHidingIsOn(false);
        }
        final double angle = getStartingAngle();
        final boolean radial_labels = getOptions().getNodeLabelDirection() == NODE_LABEL_DIRECTION.RADIAL;
        _dynamic_hiding_factor = 0;
        if (getControlPanel().isDynamicallyHideData()) {
            _dynamic_hiding_factor = (int) ((getTreeFontSet()._fm_large.getHeight() * 1.5
                    * getPhylogeny().getNumberOfExternalNodes()) / (TWO_PI * 10));
        }
        if (getControlPanel().getDynamicallyHideData() != null) {
            if (_dynamic_hiding_factor > 1) {
                getControlPanel().setDynamicHidingIsOn(true);
            } else {
                getControlPanel().setDynamicHidingIsOn(false);
            }
        }
        paintUnrooted(_phylogeny.getRoot(), angle, (float) (angle + 2 * Math.PI), radial_labels, g, to_pdf,
                to_graphics_file);
        if (getOptions().isShowScale()) {
            if (!(to_graphics_file || to_pdf)) {
                paintScale(g, getVisibleRect().x, getVisibleRect().y + getVisibleRect().height, to_pdf,
                        to_graphics_file);
            } else {
                paintScale(g, graphics_file_x, graphics_file_y + graphics_file_height, to_pdf,
                        to_graphics_file);
            }
        }
        if (getOptions().isShowOverview() && isOvOn() && !to_graphics_file && !to_pdf) {
            g.setColor(getTreeColorSet().getOvColor());
            paintUnrootedLite(_phylogeny.getRoot(), angle, angle + 2 * Math.PI, g,
                    (getUrtFactorOv() / (getVisibleRect().width / getOvMaxWidth())));
            paintOvRectangle(g);
        }
    } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR) {
        final int radius = (int) ((Math.min(getPreferredSize().getWidth(), getPreferredSize().getHeight()) / 2)
                - (MOVE + getLongestExtNodeInfo()));
        final int d = radius + MOVE + getLongestExtNodeInfo();
        _dynamic_hiding_factor = 0;
        if (getControlPanel().isDynamicallyHideData() && (radius > 0)) {
            _dynamic_hiding_factor = (int) ((getTreeFontSet()._fm_large.getHeight() * 1.5
                    * getPhylogeny().getNumberOfExternalNodes()) / (TWO_PI * radius));
        }
        if (getControlPanel().getDynamicallyHideData() != null) {
            if (_dynamic_hiding_factor > 1) {
                getControlPanel().setDynamicHidingIsOn(true);
            } else {
                getControlPanel().setDynamicHidingIsOn(false);
            }
        }
        paintCircular(_phylogeny, getStartingAngle(), d, d, radius > 0 ? radius : 0, g, to_pdf,
                to_graphics_file);
        if (getOptions().isShowOverview() && isOvOn() && !to_graphics_file && !to_pdf) {
            final int radius_ov = (int) (getOvMaxHeight() < getOvMaxWidth() ? getOvMaxHeight() / 2
                    : getOvMaxWidth() / 2);
            double x_scale = 1.0;
            double y_scale = 1.0;
            int x_pos = getVisibleRect().x + getOvXPosition();
            int y_pos = getVisibleRect().y + getOvYPosition();
            if (getWidth() > getHeight()) {
                x_scale = (double) getHeight() / getWidth();
                x_pos = ForesterUtil.roundToInt(x_pos / x_scale);
            } else {
                y_scale = (double) getWidth() / getHeight();
                y_pos = ForesterUtil.roundToInt(y_pos / y_scale);
            }
            _at = g.getTransform();
            g.scale(x_scale, y_scale);
            paintCircularLite(_phylogeny, getStartingAngle(), x_pos + radius_ov, y_pos + radius_ov,
                    (int) (radius_ov - (getLongestExtNodeInfo()
                            / (getVisibleRect().width / getOvRectangle().getWidth()))),
                    g);
            g.setTransform(_at);
            paintOvRectangle(g);
        }
    }
}

From source file:juicebox.mapcolorui.HeatmapRenderer.java

public boolean render(int originX, int originY, int width, int height, final MatrixZoomData zd,
        final MatrixZoomData controlZD, final MatrixType displayOption,
        final NormalizationType normalizationType, final ExpectedValueFunction df, Graphics2D g) {

    g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);

    int chr1 = zd.getChr1Idx();
    int chr2 = zd.getChr2Idx();
    int x = originX;
    int y = originY;

    boolean isWholeGenome = chr1 == 0 && chr2 == 0;
    boolean sameChr = (chr1 == chr2);

    if (sameChr) {
        // Data is transposable, transpose if necessary.  Convention is to use lower diagonal
        if (x > y) {
            //noinspection SuspiciousNameCombination
            x = originY;/*from  w  w w  . ja  v a2  s . c  o  m*/
            y = originX;
            int tmp = width;
            width = height;
            height = tmp;
        }
    }

    int maxX = x + width - 1;
    int maxY = y + height - 1;

    if (displayOption == MatrixType.PEARSON) {

        BasicMatrix bm = zd.getPearsons(df);

        ((HiCColorScale) pearsonColorScale).setMin(bm.getLowerValue());
        ((HiCColorScale) pearsonColorScale).setMax(bm.getUpperValue());
        renderMatrix(bm, originX, originY, width, height, pearsonColorScale, g);

    } else {
        // Iterate through blocks overlapping visible region

        List<Block> blocks = zd.getNormalizedBlocksOverlapping(x, y, maxX, maxY, normalizationType);
        if (blocks == null) {
            return false;
        }

        boolean hasControl = controlZD != null
                && (displayOption == MatrixType.CONTROL || displayOption == MatrixType.RATIO);
        Map<Integer, Block> controlBlocks = new HashMap<Integer, Block>();
        if (hasControl) {
            List<Block> ctrls = controlZD.getNormalizedBlocksOverlapping(x, y, maxX, maxY, normalizationType);
            for (Block b : ctrls) {
                controlBlocks.put(b.getNumber(), b);
            }
        }

        String key = zd.getKey() + displayOption;
        ColorScale cs = getColorScale(key, displayOption, isWholeGenome, blocks);

        double averageCount = zd.getAverageCount(); // Will get overwritten for intra-chr
        double ctrlAverageCount = controlZD == null ? 1 : controlZD.getAverageCount();
        for (Block b : blocks) {

            Collection<ContactRecord> recs = b.getContactRecords();
            if (recs != null) {

                Map<String, ContactRecord> controlRecords = new HashMap<String, ContactRecord>();
                if (hasControl) {
                    Block cb = controlBlocks.get(b.getNumber());
                    if (cb != null) {
                        for (ContactRecord ctrlRec : cb.getContactRecords()) {
                            controlRecords.put(ctrlRec.getKey(), ctrlRec);
                        }
                    }
                }

                for (ContactRecord rec : recs) {
                    double score = Double.NaN;
                    if (displayOption == MatrixType.OE || displayOption == MatrixType.EXPECTED) {
                        double expected = 0;
                        if (chr1 == chr2) {
                            if (df != null) {
                                int binX = rec.getBinX();
                                int binY = rec.getBinY();
                                int dist = Math.abs(binX - binY);
                                expected = df.getExpectedValue(chr1, dist);
                            }
                        } else {
                            expected = (averageCount > 0 ? averageCount : 1);
                        }

                        if (displayOption == MatrixType.OE) {
                            score = rec.getCounts() / expected;
                        } else {
                            score = expected;
                        }
                    } else if (displayOption == MatrixType.CONTROL && hasControl) {
                        ContactRecord ctrlRecord = controlRecords.get(rec.getKey());
                        if (ctrlRecord != null)
                            score = ctrlRecord.getCounts();
                    } else if (displayOption == MatrixType.RATIO && hasControl) {
                        ContactRecord ctrlRecord = controlRecords.get(rec.getKey());
                        if (ctrlRecord != null && ctrlRecord.getCounts() > 0) {
                            double num = rec.getCounts() / averageCount;
                            double den = ctrlRecord.getCounts() / ctrlAverageCount;
                            score = num / den;
                        }
                    } else {
                        score = rec.getCounts();
                    }
                    if (Double.isNaN(score))
                        continue;

                    Color color = cs.getColor((float) score);
                    g.setColor(color);

                    int px = rec.getBinX() - originX;
                    int py = rec.getBinY() - originY;
                    if (px > -1 && py > -1 && px <= width && py <= height) {
                        g.fillRect(px, py, HiCGlobals.BIN_PIXEL_WIDTH, HiCGlobals.BIN_PIXEL_WIDTH);
                    }

                    if (sameChr && (rec.getBinX() != rec.getBinY())) {
                        px = (rec.getBinY() - originX);
                        py = (rec.getBinX() - originY);
                        if (px > -1 && py > -1 && px <= width && py <= height) {
                            g.fillRect(px, py, HiCGlobals.BIN_PIXEL_WIDTH, HiCGlobals.BIN_PIXEL_WIDTH);
                        }
                    }
                }
            }
        }
    }
    return true;
}

From source file:org.pmedv.blackboard.components.BoardEditor.java

@Override
protected void paintComponent(Graphics g) {
    Boolean useLayerColor = (Boolean) Preferences.values
            .get("org.pmedv.blackboard.BoardDesignerPerspective.useLayerColor");

    // clear all      
    // g.clearRect(0, 0, getWidth(), getHeight());
    g.setColor(BLANK);//from  w  ww.j  av a2s. c  om
    g.fillRect(0, 0, getWidth(), getHeight());
    // some nice anti aliasing...
    Graphics2D g2 = (Graphics2D) g;
    RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2.setRenderingHints(rh);

    // TODO : Should this be done here?
    // Sort layers by z-index

    g2.setColor(Color.LIGHT_GRAY);
    g2.setStroke(BoardUtil.stroke_1_0f);

    Collections.sort(model.getLayers());
    for (int i = model.getLayers().size() - 1; i >= 0; i--) {
        // Sort items by z-index
        Collections.sort(model.getLayers().get(i).getItems());
        drawLayer(model.getLayers().get(i), g2);
    }

    // draw selection border
    if (state.equals(SelectionState.DRAGGING_NEW_SELECTION) && button1Pressed) {
        g2.setColor(Color.GREEN);
        g2.setStroke(BoardUtil.stroke_1_0f);
        if (dragStopX < dragStartX && dragStopY > dragStartY) {
            selectionBorder.setSize(dragStartX - dragStopX, dragStopY - dragStartY);
            selectionBorder.setLocation(dragStopX, dragStartY);
        } else if (dragStopY < dragStartY && dragStopX > dragStartX) {
            selectionBorder.setSize(dragStopX - dragStartX, dragStartY - dragStopY);
            selectionBorder.setLocation(dragStartX, dragStopY);
        } else if (dragStopX < dragStartX && dragStopY < dragStartY) {
            selectionBorder.setSize(dragStartX - dragStopX, dragStartY - dragStopY);
            selectionBorder.setLocation(dragStopX, dragStopY);
        } else {
            selectionBorder.setSize(dragStopX - dragStartX, dragStopY - dragStartY);
            selectionBorder.setLocation(dragStartX, dragStartY);
        }
        g2.draw(selectionBorder);
    }
    // display shape currently being drawed
    if (lineStartX > 0 && lineStartY > 0 && lineStopX > 0 && lineStopY > 0) {

        if (useLayerColor)
            g2.setColor(model.getCurrentLayer().getColor());
        else
            g2.setColor(palette.getCurrentColor());

        g2.setStroke((BasicStroke) shapesPanel.getThicknessCombo().getSelectedItem());
        // draw new line
        if (editorMode.equals(EditorMode.DRAW_LINE)) {

            if (useLayerColor)
                currentDrawingLine.setColor(model.getCurrentLayer().getColor());
            else
                currentDrawingLine.setColor(palette.getCurrentColor());

            currentDrawingLine.setStartType((LineEdgeType) shapesPanel.getStartLineCombo().getSelectedItem());
            currentDrawingLine.setEndType((LineEdgeType) shapesPanel.getEndLineCombo().getSelectedItem());
            currentDrawingLine.setStroke((BasicStroke) shapesPanel.getThicknessCombo().getSelectedItem());
            currentDrawingLine.getStart().setLocation(lineStartX, lineStartY);
            currentDrawingLine.getEnd().setLocation(lineStopX, lineStopY);
            currentDrawingLine.draw(g2);
        } else if (editorMode.equals(EditorMode.DRAW_MEASURE)) {
            currentDrawingLine.setStroke(Measure.DEFAULT_STROKE);
            currentDrawingLine.getStart().setLocation(lineStartX, lineStartY);
            currentDrawingLine.getEnd().setLocation(lineStopX, lineStopY);
            currentDrawingLine.draw(g2);
        }
        // draw new box or ellipse
        else if (editorMode.equals(EditorMode.DRAW_RECTANGLE) || editorMode.equals(EditorMode.DRAW_ELLIPSE)) {
            int xLoc = lineStartX;
            int yLoc = lineStartY;
            int width = lineStopX - lineStartX;
            int height = lineStopY - lineStartY;
            ShapeStyle style = (ShapeStyle) shapesPanel.getStyleCombo().getSelectedItem();
            if (style == null || style.equals(ShapeStyle.FILLED)) {
                if (editorMode.equals(EditorMode.DRAW_RECTANGLE)) {
                    g2.fillRect(xLoc, yLoc, width, height);
                } else {
                    g2.fillOval(xLoc, yLoc, width, height);
                }
            } else if (style.equals(ShapeStyle.OUTLINED)) {
                g2.setStroke((BasicStroke) shapesPanel.getThicknessCombo().getSelectedItem());
                if (editorMode.equals(EditorMode.DRAW_RECTANGLE)) {
                    g2.drawRect(xLoc, yLoc, width, height);
                } else {
                    g2.drawOval(xLoc, yLoc, width, height);
                }
            }
        }
    }
    // draw selection handles
    if (selectedItem != null) {
        g2.setStroke(BoardUtil.stroke_1_0f);
        g2.setColor(Color.GREEN);
        selectedItem.drawHandles(g2, 8);
    }

    // draw border

    if (zoomLayer != null) {
        TransformUI ui = (TransformUI) (Object) zoomLayer.getUI();
        DefaultTransformModel xmodel = (DefaultTransformModel) ui.getModel();

        if (xmodel.isMirror()) {
            g2.setColor(Color.RED);
        } else {
            g2.setColor(Color.GREEN);
        }
    } else {
        g2.setColor(Color.GREEN);
    }

    g2.setStroke(DEFAULT_STROKE);

    Rectangle border = new Rectangle(0, 0, model.getWidth() - 1, model.getHeight() - 1);
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
    g2.draw(border);

    if (model.getType().equals(BoardType.STRIPES) || model.getType().equals(BoardType.HOLES)) {

        g2.setColor(Color.BLACK);
        g2.setFont(miniFont);

        int index = 1;

        for (int x = 12; x < model.getWidth() - 16; x += 16) {
            g2.drawString(String.valueOf(index++), x, 8);
        }

        index = 1;

        for (int y = 18; y < model.getHeight(); y += 16) {
            g2.drawString(String.valueOf(index++), 3, y);
        }

    }

    if (editorMode.equals(EditorMode.CHECK_CONNECTIONS)) {
        if (connectedLines != null) {
            for (Line line : connectedLines) {
                line.drawFat(g2);
            }
        }
    }

    if (drawing) {

        g2.setColor(Color.BLUE);
        g2.setStroke(DEFAULT_STROKE);

        if (selectedPin != null) {
            g2.drawRect(lineStopX - 8, lineStopY - 8, 16, 16);
        }

    }

    super.paintComponents(g2);
}

From source file:org.photovault.swingui.PhotoCollectionThumbView.java

private void paintThumbnail(Graphics2D g2, PhotoInfo photo, int startx, int starty, boolean isSelected) {
    log.debug("paintThumbnail entry " + photo.getUuid());
    long startTime = System.currentTimeMillis();
    long thumbReadyTime = 0;
    long thumbDrawnTime = 0;
    long endTime = 0;
    // Current position in which attributes can be drawn
    int ypos = starty + rowHeight / 2;
    boolean useOldThumbnail = false;

    Thumbnail thumbnail = null;//from  ww w .j ava 2  s . co m
    log.debug("finding thumb");
    boolean hasThumbnail = photo.hasThumbnail();
    log.debug("asked if has thumb");
    if (hasThumbnail) {
        log.debug("Photo " + photo.getUuid() + " has thumbnail");
        thumbnail = photo.getThumbnail();
        log.debug("got thumbnail");
    } else {
        /*
         Check if the thumbnail has been just invalidated. If so, use the 
         old one until we get the new thumbnail created.
         */
        thumbnail = photo.getOldThumbnail();
        if (thumbnail != null) {
            useOldThumbnail = true;
        } else {
            // No success, use default thumnail.
            thumbnail = Thumbnail.getDefaultThumbnail();
        }

        // Inform background task scheduler that we have some work to do
        ctrl.getBackgroundTaskScheduler().registerTaskProducer(this, TaskPriority.CREATE_VISIBLE_THUMBNAIL);
    }
    thumbReadyTime = System.currentTimeMillis();

    log.debug("starting to draw");
    // Find the position for the thumbnail
    BufferedImage img = thumbnail.getImage();
    if (img == null) {
        thumbnail = Thumbnail.getDefaultThumbnail();
        img = thumbnail.getImage();
    }

    float scaleX = ((float) thumbWidth) / ((float) img.getWidth());
    float scaleY = ((float) thumbHeight) / ((float) img.getHeight());
    float scale = Math.min(scaleX, scaleY);
    int w = (int) (img.getWidth() * scale);
    int h = (int) (img.getHeight() * scale);

    int x = startx + (columnWidth - w) / (int) 2;
    int y = starty + (rowHeight - h) / (int) 2;

    log.debug("drawing thumbnail");

    // Draw shadow
    int offset = isSelected ? 2 : 0;
    int shadowX[] = { x + 3 - offset, x + w + 1 + offset, x + w + 1 + offset };
    int shadowY[] = { y + h + 1 + offset, y + h + 1 + offset, y + 3 - offset };
    GeneralPath polyline = new GeneralPath(GeneralPath.WIND_EVEN_ODD, shadowX.length);
    polyline.moveTo(shadowX[0], shadowY[0]);
    for (int index = 1; index < shadowX.length; index++) {
        polyline.lineTo(shadowX[index], shadowY[index]);
    }
    ;
    BasicStroke shadowStroke = new BasicStroke(4.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
    Stroke oldStroke = g2.getStroke();
    g2.setStroke(shadowStroke);
    g2.setColor(Color.DARK_GRAY);
    g2.draw(polyline);
    g2.setStroke(oldStroke);

    // Paint thumbnail
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2.drawImage(img, new AffineTransform(scale, 0f, 0f, scale, x, y), null);
    if (useOldThumbnail) {
        creatingThumbIcon.paintIcon(this, g2,
                startx + (columnWidth - creatingThumbIcon.getIconWidth()) / (int) 2,
                starty + (rowHeight - creatingThumbIcon.getIconHeight()) / (int) 2);
    }
    log.debug("Drawn, drawing decorations");
    if (isSelected) {
        Stroke prevStroke = g2.getStroke();
        Color prevColor = g2.getColor();
        g2.setStroke(new BasicStroke(3.0f));
        g2.setColor(Color.BLUE);
        g2.drawRect(x, y, w, h);
        g2.setColor(prevColor);
        g2.setStroke(prevStroke);
    }

    thumbDrawnTime = System.currentTimeMillis();

    boolean drawAttrs = (thumbWidth >= 100);
    if (drawAttrs) {
        // Increase ypos so that attributes are drawn under the image
        ypos += ((int) h) / 2 + 3;

        // Draw the attributes

        // Draw the qualoity icon to the upper left corner of the thumbnail
        int quality = photo.getQuality();
        if (showQuality && quality != 0) {
            int qx = startx + (columnWidth - quality * starIcon.getIconWidth()) / (int) 2;
            for (int n = 0; n < quality; n++) {
                starIcon.paintIcon(this, g2, qx, ypos);
                qx += starIcon.getIconWidth();
            }
            ypos += starIcon.getIconHeight();
        }
        ypos += 6;

        if (photo.getRawSettings() != null) {
            // Draw the "RAW" icon
            int rx = startx + (columnWidth + w - rawIcon.getIconWidth()) / (int) 2 - 5;
            int ry = starty + (columnWidth - h - rawIcon.getIconHeight()) / (int) 2 + 5;
            rawIcon.paintIcon(this, g2, rx, ry);
        }
        if (photo.getHistory().getHeads().size() > 1) {
            // Draw the "unresolved conflicts" icon
            int rx = startx + (columnWidth + w - 10) / (int) 2 - 20;
            int ry = starty + (columnWidth - h - 10) / (int) 2;
            g2.setColor(Color.RED);
            g2.fillRect(rx, ry, 10, 10);
        }

        Color prevBkg = g2.getBackground();
        if (isSelected) {
            g2.setBackground(Color.BLUE);
        } else {
            g2.setBackground(this.getBackground());
        }
        Font attrFont = new Font("Arial", Font.PLAIN, 10);
        FontRenderContext frc = g2.getFontRenderContext();
        if (showDate && photo.getShootTime() != null) {
            FuzzyDate fd = new FuzzyDate(photo.getShootTime(), photo.getTimeAccuracy());

            String dateStr = fd.format();
            TextLayout txt = new TextLayout(dateStr, attrFont, frc);
            // Calculate the position for the text
            Rectangle2D bounds = txt.getBounds();
            int xpos = startx + ((int) (columnWidth - bounds.getWidth())) / 2 - (int) bounds.getMinX();
            g2.clearRect(xpos - 2, ypos - 2, (int) bounds.getWidth() + 4, (int) bounds.getHeight() + 4);
            txt.draw(g2, xpos, (int) (ypos + bounds.getHeight()));
            ypos += bounds.getHeight() + 4;
        }
        String shootPlace = photo.getShootingPlace();
        if (showPlace && shootPlace != null && shootPlace.length() > 0) {
            TextLayout txt = new TextLayout(photo.getShootingPlace(), attrFont, frc);
            // Calculate the position for the text
            Rectangle2D bounds = txt.getBounds();
            int xpos = startx + ((int) (columnWidth - bounds.getWidth())) / 2 - (int) bounds.getMinX();

            g2.clearRect(xpos - 2, ypos - 2, (int) bounds.getWidth() + 4, (int) bounds.getHeight() + 4);
            txt.draw(g2, xpos, (int) (ypos + bounds.getHeight()));
            ypos += bounds.getHeight() + 4;
        }
        g2.setBackground(prevBkg);
    }
    endTime = System.currentTimeMillis();
    log.debug("paintThumbnail: exit " + photo.getUuid());
    log.debug("Thumb fetch " + (thumbReadyTime - startTime) + " ms");
    log.debug("Thumb draw " + (thumbDrawnTime - thumbReadyTime) + " ms");
    log.debug("Deacoration draw " + (endTime - thumbDrawnTime) + " ms");
    log.debug("Total " + (endTime - startTime) + " ms");
}