Example usage for java.awt Graphics2D setColor

List of usage examples for java.awt Graphics2D setColor

Introduction

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

Prototype

public abstract void setColor(Color c);

Source Link

Document

Sets this graphics context's current color to the specified color.

Usage

From source file:net.sf.mzmine.modules.visualization.twod.PointTwoDXYPlot.java

public boolean render(final Graphics2D g2, final Rectangle2D dataArea, int index, PlotRenderingInfo info,
        CrosshairState crosshairState) {

    // if this is not TwoDDataSet
    if (index != 0)
        return super.render(g2, dataArea, index, info, crosshairState);

    // prepare some necessary constants
    final int x = (int) dataArea.getX();
    final int y = (int) dataArea.getY();
    final int width = (int) dataArea.getWidth();
    final int height = (int) dataArea.getHeight();

    final double imageRTMin = (double) getDomainAxis().getRange().getLowerBound();
    final double imageRTMax = (double) getDomainAxis().getRange().getUpperBound();
    final double imageRTStep = (imageRTMax - imageRTMin) / width;
    final double imageMZMin = (double) getRangeAxis().getRange().getLowerBound();
    final double imageMZMax = (double) getRangeAxis().getRange().getUpperBound();
    final double imageMZStep = (imageMZMax - imageMZMin) / height;

    // This if statement below keeps the min max values at the original values when the user
    // zooms in. We need some variables that scall as the box size so that the points we show
    // have better resolution the more someone zooms in.

    double dynamicImageRTMin = imageRTMin;
    double dynamicImageRTMax = imageRTMax;
    double dynamicImageMZMin = imageMZMin;
    double dynamicImageMZMax = imageMZMax;
    double dynamicImageRTStep = imageRTStep;
    double dynamicImageMZStep = imageMZStep;

    if ((zoomOutBitmap != null) && (imageRTMin == totalRTRange.lowerEndpoint())
            && (imageRTMax == totalRTRange.upperEndpoint()) && (imageMZMin == totalMZRange.lowerEndpoint())
            && (imageMZMax == totalMZRange.upperEndpoint()) && (zoomOutBitmap.getWidth() == width)
            && (zoomOutBitmap.getHeight() == height)) {
        g2.drawImage(zoomOutBitmap, x, y, null);
        return true;
    }/*  w  w w.  j  a  v a  2s. c  o m*/

    // Save current time
    Date renderStartTime = new Date();

    // prepare a bitmap of required size
    //BufferedImage image = new BufferedImage(width, height,
    //BufferedImage.TYPE_INT_ARGB);

    //ArrayList<DataPoint> listOfDataPoints = new ArrayList<DataPoint>();
    //ArrayList<DataPoint> listOfRTValues = new ArrayList<DataPoint>();
    ArrayList<DataPoint> listOfDataPoints;
    ArrayList<Double> listOfRTValues;

    // These two function must be run in this order
    Range<Double> rtRangeIn = Range.closed(getDomainAxis().getRange().getLowerBound(),
            getDomainAxis().getRange().getUpperBound());
    Range<Double> mzRangeIn = Range.closed(getRangeAxis().getRange().getLowerBound(),
            getRangeAxis().getRange().getUpperBound());
    listOfDataPoints = dataset.getCentroidedDataPointsInRTMZRange(rtRangeIn, mzRangeIn);
    listOfRTValues = dataset.getrtValuesInUserRange();

    // points to be plotted
    List plotPoints = new ArrayList();

    int count = 0;

    // Store the current mz,rt,int values so that they can be outputed to a file if we want
    //currentlyPlottedMZ = new ArrayList();

    //for (Iterator dpIt = listOfDataPoints.iterator(); dpIt.hasNext();) {

    // make a list to keep track of the intesities of each
    for (DataPoint curDataPoint : listOfDataPoints) {

        //DataPoint curDataPoint = dpIt.next();
        double currentRT = listOfRTValues.get(count).doubleValue();
        double currentMZ = curDataPoint.getMZ();

        plotPoints.add(new Point2D.Double(currentRT, currentMZ));

        count += 1;

        //currentlyPlottedMZ.add()
    }

    // draw image points
    //for (int i = 0; i < width; i++)
    //    for (int j = 0; j < height; j++) {
    //   Color pointColor = paletteType.getColor(values[i][j]);
    //   //image.setRGB(i, height - j - 1, pointColor.getRGB());
    //    points.add(new Point2D.Float(i,j));
    //    }
    count = 0;
    for (Iterator i = plotPoints.iterator(); i.hasNext();) {
        Point2D.Double pt = (Point2D.Double) i.next();
        // using the ''dynamic'' min and max will make the resolution imporve as someone zooms
        // in 
        //float xPlace = (pt.x-(float)dynamicImageRTMin)/((float)dynamicImageRTStep) + x;
        //float yPlace = (pt.y-(float)dynamicImageMZMin)/((float)dynamicImageMZStep) + y;
        double xPlace = (pt.x - dynamicImageRTMin) / (dynamicImageRTStep) + (double) x;
        double yPlace = (double) height - (pt.y - dynamicImageMZMin) / (dynamicImageMZStep) + (double) y;

        //get the current intensity
        // use the R, G B for the intensity

        double curIntensity = listOfDataPoints.get(count).getIntensity();
        curIntensity = curIntensity / dataset.curMaxIntensity;

        //g2.setColor(Color.BLACK);
        Color pointColor = paletteType.getColor(curIntensity);
        g2.setColor(pointColor);
        Ellipse2D dot = new Ellipse2D.Double(xPlace - 1, yPlace - 1, 2, 2);
        g2.fill(dot);

        count += 1;
    }

    //float xPlace = ((float)42.0-(float)dynamicImageRTMin)/((float)dynamicImageRTStep)+x;
    //float yPlace = (float)height - ((float)201.02-(float)dynamicImageMZMin)/((float)dynamicImageMZStep)+y;
    //Ellipse2D dot = new Ellipse2D.Float(xPlace - 1, yPlace - 1, 2, 2);
    //g2.fill(dot);

    //g2.dispose();

    // if we are zoomed out, save the values
    if ((imageRTMin == totalRTRange.lowerEndpoint()) && (imageRTMax == totalRTRange.upperEndpoint())
            && (imageMZMin == totalMZRange.lowerEndpoint()) && (imageMZMax == totalMZRange.upperEndpoint())) {
        //zoomOutBitmap = image;
    }

    // Paint image
    //g2.drawImage(image, x, y, null);

    //g.setColor(Color.BLACK)

    Date renderFinishTime = new Date();

    logger.finest("Finished rendering 2D visualizer, "
            + (renderFinishTime.getTime() - renderStartTime.getTime()) + " ms");

    return true;

}

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  ww  . ja v a 2 s.co 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.forester.archaeopteryx.TreePanel.java

final private void paintNodeData(final Graphics2D g, final PhylogenyNode node, final boolean to_graphics_file,
        final boolean to_pdf, final boolean is_in_found_nodes) {
    if (isNodeDataInvisible(node) && !to_graphics_file && !to_pdf) {
        return;//from ww  w . j  av  a2 s  . c o  m
    }
    if (getOptions().isShowBranchLengthValues()
            && ((getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR)
                    || (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED)
                    || (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE))
            && (!node.isRoot()) && (node.getDistanceToParent() != PhylogenyNode.DISTANCE_DEFAULT)) {
        paintBranchLength(g, node, to_pdf, to_graphics_file);
    }
    if (!getControlPanel().isShowInternalData() && !node.isExternal() && !node.isCollapse()) {
        return;
    }
    int x = 0;
    if (node.getNodeData().isHasTaxonomy()
            && (getControlPanel().isShowTaxonomyCode() || getControlPanel().isShowTaxonomyNames())) {
        x = paintTaxonomy(g, node, is_in_found_nodes, to_pdf, to_graphics_file);
    }
    if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) {
        g.setColor(Color.BLACK);
    } else if (is_in_found_nodes) {
        g.setColor(getTreeColorSet().getFoundColor());
    } else if (getControlPanel().isColorAccordingToTaxonomy()) {
        g.setColor(getTaxonomyBasedColor(node));
    } else {
        g.setColor(getTreeColorSet().getSequenceColor());
    }
    _sb.setLength(0);
    if (node.isCollapse() && ((!node.isRoot() && !node.getParent().isCollapse()) || node.isRoot())) {
        _sb.append(" [");
        _sb.append(node.getAllExternalDescendants().size());
        _sb.append("]");
    }
    if (getControlPanel().isShowNodeNames() && (node.getNodeName().length() > 0)) {
        if (_sb.length() > 0) {
            _sb.append(" ");
        }
        _sb.append(node.getNodeName());
    }
    if (node.getNodeData().isHasSequence()) {
        if (getControlPanel().isShowGeneSymbols()
                && (node.getNodeData().getSequence().getSymbol().length() > 0)) {
            if (_sb.length() > 0) {
                _sb.append(" ");
            }
            _sb.append(node.getNodeData().getSequence().getSymbol());
        }
        if (getControlPanel().isShowGeneNames() && (node.getNodeData().getSequence().getName().length() > 0)) {
            //                if ( _sb.length() > 0 ) {
            //                    _sb.append( " " );
            //                }
            //                _sb.append( node.getNodeData().getSequence().getName() );
            PhylogenyNode parent = node.getParent();
            double x1 = parent.getXcoord();
            double y1 = parent.getYcoord();
            double x2 = node.getXcoord();
            double y2 = node.getYcoord();
            double above_the_line = 1.0;

            if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.TRIANGULAR) {
                double center_of_branch_x = Math.abs(x1 + x2) / 2.0;
                double center_of_branch_y = Math.abs(y1 + y2) / 2.0;
                TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x,
                        center_of_branch_y - above_the_line, g);
            } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR) {
                double center_of_branch_x = Math.abs(x1 + x2) / 2.0;
                double center_of_branch_y = y2;
                TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x,
                        center_of_branch_y - above_the_line, g);
            } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED) {
                double center_of_branch_x = Math.abs(x1 + x2) / 2.0;
                double center_of_branch_y = y2;
                TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x,
                        center_of_branch_y - above_the_line, g);
            } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE) {
                double center_of_branch_x = Math.abs(x1 + x2) / 2.0 + EURO_D;
                double center_of_branch_y = y2;
                TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x,
                        center_of_branch_y - above_the_line, g);
            }

        }
        if (getControlPanel().isShowSequenceAcc()
                && (node.getNodeData().getSequence().getAccession() != null)) {
            if (_sb.length() > 0) {
                _sb.append(" ");
            }
            if (!ForesterUtil.isEmpty(node.getNodeData().getSequence().getAccession().getSource())) {
                _sb.append(node.getNodeData().getSequence().getAccession().getSource());
                _sb.append(":");
            }
            _sb.append(node.getNodeData().getSequence().getAccession().getValue());
        }
    }
    g.setFont(getTreeFontSet().getLargeFont());
    if (is_in_found_nodes) {
        g.setFont(getTreeFontSet().getLargeFont().deriveFont(Font.BOLD));
    }
    double down_shift_factor = 3.0;
    if (!node.isExternal() && (node.getNumberOfDescendants() == 1)) {
        down_shift_factor = 1;
    }
    // GUILHEM_BEG ______________
    final double posX = node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE;
    final double posY = (node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor));
    final int CONFIDENCE_LEFT_MARGIN = 4;
    final String sNodeText = _sb.toString();
    if (_control_panel.isShowSequenceRelations() && node.getNodeData().isHasSequence()
            && (_query_sequence != null)) {
        int nodeTextBoundsWidth = 0;
        if (sNodeText.length() > 0) {
            final Rectangle2D node_text_bounds = new TextLayout(sNodeText, g.getFont(), _frc).getBounds(); //would like to remove this 'new', but how...
            nodeTextBoundsWidth = (int) node_text_bounds.getWidth();
        }
        if (node.getNodeData().getSequence().equals(_query_sequence)) {
            if (nodeTextBoundsWidth > 0) { // invert font color and background color to show that this is the query sequence
                g.fillRect((int) posX - 1, (int) posY - 8, nodeTextBoundsWidth + 5, 11);
                g.setColor(getTreeColorSet().getBackgroundColor());
            }
        } else {
            final List<SequenceRelation> seqRelations = node.getNodeData().getSequence().getSequenceRelations();
            for (final SequenceRelation seqRelation : seqRelations) {
                final boolean fGotRelationWithQuery = (seqRelation.getRef0().isEqual(_query_sequence)
                        || seqRelation.getRef1().isEqual(_query_sequence))
                        && seqRelation.getType()
                                .equals(getControlPanel().getSequenceRelationTypeBox().getSelectedItem());
                if (fGotRelationWithQuery) { // we will underline the text to show that this sequence is ortholog to the query
                    final double linePosX = node.getXcoord() + 2 + TreePanel.HALF_BOX_SIZE;
                    final String sConfidence = (!getControlPanel().isShowSequenceRelationConfidence()
                            || (seqRelation.getConfidence() == null)) ? null
                                    : " (" + seqRelation.getConfidence().getValue() + ")";
                    if (sConfidence != null) {
                        double confidenceX = posX;
                        if (sNodeText.length() > 0) {
                            confidenceX += new TextLayout(sNodeText, g.getFont(), _frc).getBounds().getWidth()
                                    + CONFIDENCE_LEFT_MARGIN;
                        }
                        if (confidenceX > linePosX) { // let's only display confidence value if we are already displaying at least one of Prot/Gene Name and Taxonomy Code 
                            final int confidenceWidth = (int) new TextLayout(sConfidence, g.getFont(), _frc)
                                    .getBounds().getWidth();
                            TreePanel.drawString(sConfidence, confidenceX, posY, g);
                            x += CONFIDENCE_LEFT_MARGIN + confidenceWidth;
                        }
                    }
                    if (x + nodeTextBoundsWidth > 0) /* we only underline if there is something displayed */
                    {
                        if (nodeTextBoundsWidth == 0) {
                            nodeTextBoundsWidth -= 3; /* the gap between taxonomy code and node name should not be underlined if nothing comes after it */
                        } else {
                            nodeTextBoundsWidth += 2;
                        }
                        g.drawLine((int) linePosX + 1, 3 + (int) posY, (int) linePosX + x + nodeTextBoundsWidth,
                                3 + (int) posY);
                        break;
                    }
                }
            }
        }
    }
    if (sNodeText.length() > 0) {
        TreePanel.drawString(sNodeText, posX, posY, g);
    }
    // GUILHEM_END _____________
    // COMMENTED_OUT_BY_GUILHEM_BEG _______________
    // TODO FIXME need to check this one!
    //if ( _sb.length() > 0 ) {
    //    TreePanel.drawString( _sb.toString(), node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE, node.getYcoord()
    //            + ( getTreeFontSet()._fm_large.getAscent() / down_shift_factor ), g );
    //}
    // COMMENTED_OUT_BY_GUILHEM_END ________________
    if (getControlPanel().isShowAnnotation() && node.getNodeData().isHasSequence()
            && (node.getNodeData().getSequence().getAnnotations() != null)
            && (!node.getNodeData().getSequence().getAnnotations().isEmpty())) {
        if (_sb.length() > 0) {
            x += getTreeFontSet()._fm_large.stringWidth(_sb.toString()) + 5;
        }
        final Annotation ann = (Annotation) node.getNodeData().getSequence().getAnnotations().get(0);
        if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) {
            g.setColor(Color.BLACK);
        } else {
            g.setColor(calculateColorForAnnotation(ann));
        }
        final String ann_str = ann.asSimpleText().toString();
        TreePanel.drawString(ann_str, node.getXcoord() + x + 3 + TreePanel.HALF_BOX_SIZE,
                node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor), g);
        _sb.setLength(0);
        _sb.append(ann_str);
    }
    if ((getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR)
            || (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE)
            || (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED)) {
        if ((getControlPanel().isShowBinaryCharacters() || getControlPanel().isShowBinaryCharacterCounts())
                && node.getNodeData().isHasBinaryCharacters()) {
            if (_sb.length() > 0) {
                x += getTreeFontSet()._fm_large.stringWidth(_sb.toString()) + 5;
            }
            if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) {
                g.setColor(Color.BLACK);
            } else {
                g.setColor(getTreeColorSet().getBinaryDomainCombinationsColor());
            }
            if (getControlPanel().isShowBinaryCharacters()) {
                TreePanel.drawString(
                        node.getNodeData().getBinaryCharacters().getPresentCharactersAsStringBuffer()
                                .toString(),
                        node.getXcoord() + x + 1 + TreePanel.HALF_BOX_SIZE,
                        node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor), g);
                paintGainedAndLostCharacters(g, node,
                        node.getNodeData().getBinaryCharacters().getGainedCharactersAsStringBuffer().toString(),
                        node.getNodeData().getBinaryCharacters().getLostCharactersAsStringBuffer().toString());
            } else {
                if (DRAW_MEAN_COUNTS && node.isInternal()) {
                    final List<PhylogenyNode> ec = node.getAllExternalDescendants();
                    double sum = 0;
                    int count = 0;
                    for (final PhylogenyNode phylogenyNode : ec) {
                        count++;
                        if (phylogenyNode.getNodeData().getBinaryCharacters() != null) {
                            sum += phylogenyNode.getNodeData().getBinaryCharacters().getPresentCount();
                        }
                    }
                    final double mean = ForesterUtil.round(sum / count, 1);
                    TreePanel.drawString(
                            node.getNodeData().getBinaryCharacters().getPresentCount() + " [" + mean + "]",
                            node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE,
                            node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor), g);
                } else {
                    TreePanel.drawString(node.getNodeData().getBinaryCharacters().getPresentCount(),
                            node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE,
                            node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor), g);
                }
                paintGainedAndLostCharacters(g, node,
                        "+" + node.getNodeData().getBinaryCharacters().getGainedCount(),
                        "-" + node.getNodeData().getBinaryCharacters().getLostCount());
            }
        }
    }
}

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

final private void paintUnrootedLite(final PhylogenyNode n, final double low_angle, final double high_angle,
        final Graphics2D g, final float urt_ov_factor) {

    if (n.isRoot()) {
        final int x_pos = (int) (getVisibleRect().x + getOvXPosition() + getOvMaxWidth() / 2);
        final int y_pos = (int) (getVisibleRect().y + getOvYPosition() + getOvMaxHeight() / 2);
        n.setXSecondary(x_pos);//from w  w w .j  a  va2s .  c o  m
        n.setYSecondary(y_pos);
    }
    if (n.isExternal()) {
        return;
    }
    final float num_enclosed = n.getNumberOfExternalNodes();
    final float x = n.getXSecondary();
    final float y = n.getYSecondary();
    double current_angle = low_angle;
    for (int i = 0; i < n.getNumberOfDescendants(); ++i) {
        final PhylogenyNode desc = n.getChildNode(i);
        final int desc_num_enclosed = desc.getNumberOfExternalNodes();
        final double arc_size = (desc_num_enclosed / num_enclosed) * (high_angle - low_angle);
        float length;
        if (isPhyHasBranchLengths() && getControlPanel().isDrawPhylogram()) {
            if (desc.getDistanceToParent() < 0) {
                length = 0;
            } else {
                length = (float) (desc.getDistanceToParent() * urt_ov_factor);
            }
        } else {
            length = urt_ov_factor;
        }
        final double mid_angle = current_angle + arc_size / 2;
        final float new_x = (float) (x + Math.cos(mid_angle) * length);
        final float new_y = (float) (y + Math.sin(mid_angle) * length);
        desc.setXSecondary(new_x);
        desc.setYSecondary(new_y);
        if (isInFoundNodes(desc)) {
            g.setColor(getTreeColorSet().getFoundColor());
            drawRectFilled(desc.getXSecondary() - 1, desc.getYSecondary() - 1, 3, 3, g);
            g.setColor(getTreeColorSet().getOvColor());
        }
        paintUnrootedLite(desc, current_angle, current_angle + arc_size, g, urt_ov_factor);
        current_angle += arc_size;
        drawLine(x, y, new_x, new_y, g);
    }
}

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

final private void paintConfidenceValues(final Graphics2D g, final PhylogenyNode node, final boolean to_pdf,
        final boolean to_graphics_file) {
    String conf_str = "";
    final List<Confidence> confidences = node.getBranchData().getConfidences();
    if (confidences.size() == 1) {
        final double value = node.getBranchData().getConfidence(0).getValue();
        if ((value == Confidence.CONFIDENCE_DEFAULT_VALUE) || (value < getOptions().getMinConfidenceValue())) {
            return;
        }//from   ww w  .  j a v  a  2s . c  o  m
        conf_str = FORMATTER_CONFIDENCE.format(value);
    } else if (confidences.size() > 1) {
        boolean one_ok = false;
        boolean not_first = false;
        Collections.sort(confidences);
        final StringBuilder sb = new StringBuilder();
        for (final Confidence confidence : confidences) {
            final double value = confidence.getValue();
            if (value != Confidence.CONFIDENCE_DEFAULT_VALUE) {
                if (value >= getOptions().getMinConfidenceValue()) {
                    one_ok = true;
                }
                if (not_first) {
                    sb.append("/");
                } else {
                    not_first = true;
                }
                sb.append(FORMATTER_CONFIDENCE.format(ForesterUtil.round(value,
                        getOptions().getNumberOfDigitsAfterCommaForConfidenceValues())));
            }
        }
        if (one_ok) {
            conf_str = sb.toString();
        }
    }
    if (conf_str.length() > 0) {
        final double parent_x = node.getParent().getXcoord();
        double x = node.getXcoord();
        g.setFont(getTreeFontSet().getSmallFont());
        if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE) {
            x += EURO_D;
        } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED) {
            x += ROUNDED_D;
        }
        if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) {
            g.setColor(Color.BLACK);
        } else {
            g.setColor(getTreeColorSet().getConfidenceColor());
        }
        TreePanel.drawString(conf_str,
                parent_x + ((x - parent_x - getTreeFontSet()._fm_small.stringWidth(conf_str)) / 2),
                (node.getYcoord() + getTreeFontSet()._small_max_ascent) - 1, g);
    }
}

From source file:com.igormaznitsa.jhexed.swing.editor.ui.exporters.PNGImageExporter.java

public BufferedImage generateImage() throws IOException {
    final int DEFAULT_CELL_WIDTH = 48;
    final int DEFAULT_CELL_HEIGHT = 48;

    final int imgWidth = this.docOptions.getImage() == null ? DEFAULT_CELL_WIDTH * this.docOptions.getColumns()
            : Math.round(this.docOptions.getImage().getSVGWidth());
    final int imgHeight = this.docOptions.getImage() == null ? DEFAULT_CELL_HEIGHT * this.docOptions.getRows()
            : Math.round(this.docOptions.getImage().getSVGHeight());

    final BufferedImage result;
    if (exportData.isBackgroundImageExport() && this.docOptions.getImage() != null) {
        result = this.docOptions.getImage().rasterize(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
    } else {/*from www  .j  a va  2  s  . c  o m*/
        result = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
    }

    final Graphics2D gfx = result.createGraphics();
    gfx.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    gfx.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    final HexEngine<Graphics2D> engine = new HexEngine<Graphics2D>(DEFAULT_CELL_WIDTH, DEFAULT_CELL_HEIGHT,
            this.docOptions.getHexOrientation());

    final List<HexFieldLayer> reversedNormalizedStack = new ArrayList<HexFieldLayer>();
    for (int i = this.exportData.getLayers().size() - 1; i >= 0; i--) {
        final LayerExportRecord rec = this.exportData.getLayers().get(i);
        if (rec.isAllowed()) {
            reversedNormalizedStack.add(rec.getLayer());
        }
    }

    if (Thread.currentThread().isInterrupted())
        return null;

    final HexFieldValue[] stackOfValues = new HexFieldValue[reversedNormalizedStack.size()];

    engine.setModel(new HexEngineModel<HexFieldValue[]>() {

        @Override
        public int getColumnNumber() {
            return docOptions.getColumns();
        }

        @Override
        public int getRowNumber() {
            return docOptions.getRows();
        }

        @Override
        public HexFieldValue[] getValueAt(final int col, final int row) {
            Arrays.fill(stackOfValues, null);

            for (int index = 0; index < reversedNormalizedStack.size(); index++) {
                stackOfValues[index] = reversedNormalizedStack.get(index).getHexValueAtPos(col, row);
            }
            return stackOfValues;
        }

        @Override
        public HexFieldValue[] getValueAt(final HexPosition pos) {
            return this.getValueAt(pos.getColumn(), pos.getRow());
        }

        @Override
        public void setValueAt(int col, int row, HexFieldValue[] value) {
        }

        @Override
        public void setValueAt(HexPosition pos, HexFieldValue[] value) {
        }

        @Override
        public boolean isPositionValid(final int col, final int row) {
            return col >= 0 && col < docOptions.getColumns() && row >= 0 && row < docOptions.getRows();
        }

        @Override
        public boolean isPositionValid(final HexPosition pos) {
            return this.isPositionValid(pos.getColumn(), pos.getRow());
        }

        @Override
        public void attachedToEngine(final HexEngine<?> engine) {
        }

        @Override
        public void detachedFromEngine(final HexEngine<?> engine) {
        }
    });

    final HexRect2D visibleSize = engine.getVisibleSize();
    final float xcoeff = (float) result.getWidth() / visibleSize.getWidth();
    final float ycoeff = (float) result.getHeight() / visibleSize.getHeight();
    engine.setScale(xcoeff, ycoeff);

    final Image[][] cachedIcons = new Image[this.exportData.getLayers().size()][];
    engine.setRenderer(new ColorHexRender() {

        private final Stroke stroke = new BasicStroke(docOptions.getLineWidth());

        @Override
        public Stroke getStroke() {
            return this.stroke;
        }

        @Override
        public Color getFillColor(HexEngineModel<?> model, int col, int row) {
            return null;
        }

        @Override
        public Color getBorderColor(HexEngineModel<?> model, int col, int row) {
            return exportData.isExportHexBorders() ? docOptions.getColor() : null;
        }

        @Override
        public void drawExtra(HexEngine<Graphics2D> engine, Graphics2D g, int col, int row, Color borderColor,
                Color fillColor) {
        }

        @Override
        public void drawUnderBorder(final HexEngine<Graphics2D> engine, final Graphics2D g, final int col,
                final int row, final Color borderColor, final Color fillColor) {
            final HexFieldValue[] stackValues = (HexFieldValue[]) engine.getModel().getValueAt(col, row);
            for (int i = 0; i < stackValues.length; i++) {
                final HexFieldValue valueToDraw = stackValues[i];
                if (valueToDraw == null) {
                    continue;
                }
                g.drawImage(cachedIcons[i][valueToDraw.getIndex()], 0, 0, null);
            }
        }

    });

    final Path2D hexShape = ((ColorHexRender) engine.getRenderer()).getHexPath();
    final int cellWidth = hexShape.getBounds().width;
    final int cellHeight = hexShape.getBounds().height;

    for (int layerIndex = 0; layerIndex < reversedNormalizedStack.size()
            && !Thread.currentThread().isInterrupted(); layerIndex++) {
        final HexFieldLayer theLayer = reversedNormalizedStack.get(layerIndex);
        final Image[] cacheLineForLayer = new Image[theLayer.getHexValuesNumber()];
        for (int valueIndex = 1; valueIndex < theLayer.getHexValuesNumber(); valueIndex++) {
            cacheLineForLayer[valueIndex] = theLayer.getHexValueForIndex(valueIndex).makeIcon(cellWidth,
                    cellHeight, hexShape, true);
        }
        cachedIcons[layerIndex] = cacheLineForLayer;
    }

    engine.drawWithThreadInterruptionCheck(gfx);
    if (Thread.currentThread().isInterrupted())
        return null;

    if (this.exportData.isCellCommentariesExport()) {
        final Iterator<Entry<HexPosition, String>> iterator = this.cellComments.iterator();
        gfx.setFont(new Font("Arial", Font.BOLD, 12));
        while (iterator.hasNext() && !Thread.currentThread().isInterrupted()) {
            final Entry<HexPosition, String> item = iterator.next();
            final HexPosition pos = item.getKey();
            final String text = item.getValue();
            final float x = engine.calculateX(pos.getColumn(), pos.getRow());
            final float y = engine.calculateY(pos.getColumn(), pos.getRow());

            final Rectangle2D textBounds = gfx.getFontMetrics().getStringBounds(text, gfx);

            final float dx = x - ((float) textBounds.getWidth() - engine.getCellWidth()) / 2;

            gfx.setColor(Color.BLACK);
            gfx.drawString(text, dx, y);
            gfx.setColor(Color.WHITE);
            gfx.drawString(text, dx - 2, y - 2);
        }
    }

    gfx.dispose();

    return result;
}

From source file:lu.fisch.unimozer.Diagram.java

@Override
public void paint(Graphics graphics) {
    super.paint(graphics);
    Graphics2D g = (Graphics2D) graphics;
    // set anti-aliasing rendering
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g.setFont(new Font(g.getFont().getFontName(), Font.PLAIN, Unimozer.DRAW_FONT_SIZE));

    // clear background
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, getWidth() + 1, getHeight() + 1);
    g.setColor(Color.BLACK);//w ww .  j a  v a  2 s .com

    /*Set<String> set;
    Iterator<String> itr;
    // draw classes a first time
    for(MyClass clas : classes.values())
    {
      clas.setEnabled(this.isEnabled());
      clas.draw(graphics,showFields,showMethods);
    }*/

    /* let's try this one ... */
    for (Entry<String, MyClass> entry : classes.entrySet()) {
        // get the actual class ...
        MyClass clas = entry.getValue();
        clas.setEnabled(this.isEnabled());
        clas.draw(graphics, showFields, showMethods);
    }

    // draw packages
    packages.clear();
    for (MyClass myClass : classes.values()) {
        if (myClass.isDisplayUML()) {
            Package myPackage = null;
            if (!packages.containsKey(myClass.getPackagename())) {
                myPackage = new Package(myClass.getPackagename(), myClass.getPosition().y,
                        myClass.getPosition().x, myClass.getWidth(), myClass.getHeight());
                packages.put(myPackage.getName(), myPackage);
            } else
                myPackage = packages.get(myClass.getPackagename());

            if (myClass.getPosition().x + myClass.getWidth() > myPackage.getRight())
                myPackage.setRight(myClass.getPosition().x + myClass.getWidth());
            if (myClass.getPosition().y + myClass.getHeight() > myPackage.getBottom())
                myPackage.setBottom(myClass.getPosition().y + myClass.getHeight());

            if (myClass.getPosition().x < myPackage.getLeft())
                myPackage.setLeft(myClass.getPosition().x);
            if (myClass.getPosition().y < myPackage.getTop())
                myPackage.setTop(myClass.getPosition().y);
        }
    }

    // draw classes
    /*
    set = classes.keySet();
    itr = set.iterator();
    while (itr.hasNext())
    {
      String str = itr.next();
      classes.get(str).draw(graphics);
    }/**/

    mostRight = 0;
    mostBottom = 0;

    // ??
    /*
    set = classes.keySet();
    itr = set.iterator();
    while (itr.hasNext())
    {
      String str = itr.next();
      MyClass thisClass = classes.get(str);
    }
    */

    // init topLeft & bottomRight
    topLeft = new Point(this.getWidth(), this.getHeight());
    bottomRight = new Point(0, 0);

    // draw packages
    if (packages.size() > 0)
        if ((packages.size() == 1 && packages.get(Package.DEFAULT) == null) || packages.size() > 1)
            for (Package pack : packages.values()) {
                pack.draw(graphics);
                // push outer box
                if (pack.getTopAbs() < topLeft.y)
                    topLeft.y = pack.getTopAbs();
                if (pack.getLeftAbs() < topLeft.x)
                    topLeft.x = pack.getLeftAbs();
                if (pack.getBottomAbs() > bottomRight.y)
                    bottomRight.y = pack.getBottomAbs();
                if (pack.getRightAbs() > bottomRight.x)
                    bottomRight.x = pack.getRightAbs();
            }

    // draw implmementations
    if (isShowHeritage()) {
        Stroke oldStroke = g.getStroke();
        g.setStroke(dashed);

        /*itr = set.iterator();
        while (itr.hasNext())
        {
          String str = itr.next();
        */

        /* let's try this one ... */
        for (Entry<String, MyClass> entry : classes.entrySet()) {
            // get the actual class ...
            String str = entry.getKey();

            MyClass thisClass = classes.get(str);

            if (thisClass.getPosition().x + thisClass.getWidth() > mostRight)
                mostRight = thisClass.getPosition().x + thisClass.getWidth();
            if (thisClass.getPosition().y + thisClass.getHeight() > mostBottom)
                mostBottom = thisClass.getPosition().y + thisClass.getHeight();

            if (thisClass.getImplements().size() > 0)
                for (String extendsClass : thisClass.getImplements()) {
                    MyClass otherClass = classes.get(extendsClass);
                    if (otherClass == null)
                        otherClass = findByShortName(extendsClass);
                    //if(otherClass==null) System.err.println(extendsClass+" not found (1)");
                    //if (otherClass==null) otherClass=findByShortName(extendsClass);
                    //if(otherClass==null) System.err.println(extendsClass+" not found (2)");
                    if (otherClass != null && thisClass.isDisplayUML() && otherClass.isDisplayUML()) {
                        thisClass.setExtendsMyClass(otherClass);
                        // draw arrow from thisClass to otherClass

                        // get the center point of each class
                        Point fromP = new Point(thisClass.getPosition().x + thisClass.getWidth() / 2,
                                thisClass.getPosition().y + thisClass.getHeight() / 2);
                        Point toP = new Point(otherClass.getPosition().x + otherClass.getWidth() / 2,
                                otherClass.getPosition().y + otherClass.getHeight() / 2);

                        // get the corner 4 points of the desstination class
                        // (outer margin = 4)
                        Point toP1 = new Point(otherClass.getPosition().x - 4, otherClass.getPosition().y - 4);
                        Point toP2 = new Point(otherClass.getPosition().x + otherClass.getWidth() + 4,
                                otherClass.getPosition().y - 4);
                        Point toP3 = new Point(otherClass.getPosition().x + otherClass.getWidth() + 4,
                                otherClass.getPosition().y + otherClass.getHeight() + 4);
                        Point toP4 = new Point(otherClass.getPosition().x - 4,
                                otherClass.getPosition().y + otherClass.getHeight() + 4);

                        // get the intersection with the center line an one of the
                        // sedis of the destination class
                        Point2D toDraw = getIntersection(fromP, toP, toP1, toP2);
                        if (toDraw == null)
                            toDraw = getIntersection(fromP, toP, toP2, toP3);
                        if (toDraw == null)
                            toDraw = getIntersection(fromP, toP, toP3, toP4);
                        if (toDraw == null)
                            toDraw = getIntersection(fromP, toP, toP4, toP1);

                        // draw the arrowed line
                        if (toDraw != null)
                            drawExtends(g, fromP, new Point((int) toDraw.getX(), (int) toDraw.getY()));

                    }
                }

        }
        g.setStroke(oldStroke);
    }

    // draw inheritance
    if (isShowHeritage()) {
        /*itr = set.iterator();
        while (itr.hasNext())
        {
          String str = itr.next();
        */

        /* let's try this one ... */
        for (Entry<String, MyClass> entry : classes.entrySet()) {
            // get the actual class ...
            String str = entry.getKey();

            MyClass thisClass = classes.get(str);

            if (thisClass.getPosition().x + thisClass.getWidth() > mostRight)
                mostRight = thisClass.getPosition().x + thisClass.getWidth();
            if (thisClass.getPosition().y + thisClass.getHeight() > mostBottom)
                mostBottom = thisClass.getPosition().y + thisClass.getHeight();

            String extendsClass = thisClass.getExtendsClass();
            //System.out.println(thisClass.getFullName()+" extends "+extendsClass);
            if (!extendsClass.equals("") && thisClass.isDisplayUML()) {
                MyClass otherClass = classes.get(extendsClass);
                if (otherClass == null)
                    otherClass = findByShortName(extendsClass);
                //if(otherClass==null) System.err.println(extendsClass+" not found (1)");
                //if (otherClass==null) otherClass=findByShortName(extendsClass);
                //if(otherClass==null) System.err.println(extendsClass+" not found (2)");
                if (otherClass != null) {
                    if (otherClass != thisClass) {
                        thisClass.setExtendsMyClass(otherClass);
                        // draw arrow from thisClass to otherClass

                        // get the center point of each class
                        Point fromP = new Point(thisClass.getPosition().x + thisClass.getWidth() / 2,
                                thisClass.getPosition().y + thisClass.getHeight() / 2);
                        Point toP = new Point(otherClass.getPosition().x + otherClass.getWidth() / 2,
                                otherClass.getPosition().y + otherClass.getHeight() / 2);

                        // get the corner 4 points of the desstination class
                        // (outer margin = 4)
                        Point toP1 = new Point(otherClass.getPosition().x - 4, otherClass.getPosition().y - 4);
                        Point toP2 = new Point(otherClass.getPosition().x + otherClass.getWidth() + 4,
                                otherClass.getPosition().y - 4);
                        Point toP3 = new Point(otherClass.getPosition().x + otherClass.getWidth() + 4,
                                otherClass.getPosition().y + otherClass.getHeight() + 4);
                        Point toP4 = new Point(otherClass.getPosition().x - 4,
                                otherClass.getPosition().y + otherClass.getHeight() + 4);

                        // get the intersection with the center line an one of the
                        // sedis of the destination class
                        Point2D toDraw = getIntersection(fromP, toP, toP1, toP2);
                        if (toDraw == null)
                            toDraw = getIntersection(fromP, toP, toP2, toP3);
                        if (toDraw == null)
                            toDraw = getIntersection(fromP, toP, toP3, toP4);
                        if (toDraw == null)
                            toDraw = getIntersection(fromP, toP, toP4, toP1);

                        // draw in red if there is a cclic inheritance problem
                        if (thisClass.hasCyclicInheritance()) {
                            ((Graphics2D) graphics).setStroke(new BasicStroke(2));
                            graphics.setColor(Color.RED);
                        }

                        // draw the arrowed line
                        if (toDraw != null)
                            drawExtends((Graphics2D) graphics, fromP,
                                    new Point((int) toDraw.getX(), (int) toDraw.getY()));

                    } else {
                        ((Graphics2D) graphics).setStroke(new BasicStroke(2));
                        graphics.setColor(Color.RED);

                        // line
                        graphics.drawLine(thisClass.getPosition().x + thisClass.getWidth() / 2,
                                thisClass.getPosition().y, thisClass.getPosition().x + thisClass.getWidth() / 2,
                                thisClass.getPosition().y - 32);
                        graphics.drawLine(thisClass.getPosition().x + thisClass.getWidth() / 2,
                                thisClass.getPosition().y - 32,
                                thisClass.getPosition().x + thisClass.getWidth() + 32,
                                thisClass.getPosition().y - 32);
                        graphics.drawLine(thisClass.getPosition().x + thisClass.getWidth() + 32,
                                thisClass.getPosition().y - 32,
                                thisClass.getPosition().x + thisClass.getWidth() + 32,
                                thisClass.getPosition().y + thisClass.getHeight() + 32);
                        graphics.drawLine(thisClass.getPosition().x + thisClass.getWidth() + 32,
                                thisClass.getPosition().y + thisClass.getHeight() + 32,
                                thisClass.getPosition().x + thisClass.getWidth() / 2,
                                thisClass.getPosition().y + thisClass.getHeight() + 32);
                        drawExtends((Graphics2D) graphics,
                                new Point(thisClass.getPosition().x + thisClass.getWidth() / 2,
                                        thisClass.getPosition().y + thisClass.getHeight() + 32),
                                new Point(thisClass.getPosition().x + thisClass.getWidth() / 2,
                                        thisClass.getPosition().y + thisClass.getHeight()));
                    }

                    // reset the stroke and the color
                    ((Graphics2D) graphics).setStroke(new BasicStroke(1));
                    graphics.setColor(Color.BLACK);
                }
            }
        }
    }

    // setup a hastable to store the relations
    //Hashtable<String,StringList> classUsage = new Hashtable<String,StringList>();

    // store compositions
    Hashtable<MyClass, Vector<MyClass>> classCompositions = new Hashtable<MyClass, Vector<MyClass>>();
    // store aggregations
    Hashtable<MyClass, Vector<MyClass>> classAggregations = new Hashtable<MyClass, Vector<MyClass>>();
    // store all relations
    Hashtable<MyClass, Vector<MyClass>> classUsings = new Hashtable<MyClass, Vector<MyClass>>();

    /*
    // iterate through all classes to find compositions
    itr = set.iterator();
    while (itr.hasNext())
    {
      // get the actual classname
      String str = itr.next();
    */

    /* let's try this one ... */
    for (Entry<String, MyClass> entry : classes.entrySet()) {
        // get the actual class ...
        String str = entry.getKey();

        // get the corresponding "MyClass" object
        MyClass thisClass = classes.get(str);
        // setup a list to store the relations with this class
        Vector<MyClass> theseCompositions = new Vector<MyClass>();

        // get all fields of this class
        StringList uses = thisClass.getFieldTypes();
        for (int u = 0; u < uses.count(); u++) {
            // try to find the other (used) class
            MyClass otherClass = classes.get(uses.get(u));
            if (otherClass == null)
                otherClass = findByShortName(uses.get(u));
            if (otherClass != null) // means this class uses the other ones
            {
                // add the other class to the list
                theseCompositions.add(otherClass);
            }
        }

        // add the list of used classes to the MyClass object
        thisClass.setUsesMyClass(theseCompositions);
        // store the composition in the general list
        classCompositions.put(thisClass, theseCompositions);
        // store the compositions int eh global relation list
        classUsings.put(thisClass, new Vector<MyClass>(theseCompositions));
        //                        ^^^^^^^^^^^^^^^^^^^^
        //    important !! => create a new vector, otherwise the list
        //                    are the same ...
    }

    /*
    // iterate through all classes to find aggregations
    itr = set.iterator();
    while (itr.hasNext())
    {
      // get the actual class
      String str = itr.next();
    */

    /* let's try this one ... */
    for (Entry<String, MyClass> entry : classes.entrySet()) {
        // get the actual class ...
        String str = entry.getKey();

        // get the corresponding "MyClass" object
        MyClass thisClass = classes.get(str);
        // we need a list to store the aggragations with this class
        Vector<MyClass> theseAggregations = new Vector<MyClass>();
        // try to get the list of compositions for this class
        // init if not present
        Vector<MyClass> theseCompositions = classCompositions.get(thisClass);
        if (theseCompositions == null)
            theseCompositions = new Vector<MyClass>();
        // try to get the list of all relations for this class
        // init if not present
        Vector<MyClass> theseClasses = classUsings.get(thisClass);
        if (theseClasses == null)
            theseClasses = new Vector<MyClass>();

        // get the names of the classes that thisclass uses
        StringList foundUsage = thisClass.getUsesWho();
        // go through the list an check to find a corresponding MyClass
        for (int f = 0; f < foundUsage.count(); f++) {
            // get the name of the used class
            String usedClass = foundUsage.get(f);

            MyClass otherClass = classes.get(usedClass);
            if (otherClass == null)
                otherClass = findByShortName(usedClass);
            if (otherClass != null && thisClass != otherClass)
            // meanint "otherClass" is a class used by thisClass
            {
                if (!theseCompositions.contains(otherClass))
                    theseAggregations.add(otherClass);
                if (!theseClasses.contains(otherClass))
                    theseClasses.add(otherClass);
            }
        }

        // get all method types of this class
        StringList uses = thisClass.getMethodTypes();
        for (int u = 0; u < uses.count(); u++) {
            // try to find the other (used) class
            MyClass otherClass = classes.get(uses.get(u));
            if (otherClass == null)
                otherClass = findByShortName(uses.get(u));
            if (otherClass != null) // means this class uses the other ones
            {
                // add the other class to the list
                theseAggregations.add(otherClass);
            }
        }

        // store the relations to the class
        thisClass.setUsesMyClass(theseClasses);
        // store the aggregation to the global list
        classAggregations.put(thisClass, theseAggregations);
        // store all relations to the global list
        classUsings.put(thisClass, theseClasses);
    }

    if (isShowComposition()) {
        /*Set<MyClass> set2 = classCompositions.keySet();
        Iterator<MyClass> itr2 = set2.iterator();
        while (itr2.hasNext())
        {
          MyClass thisClass = itr2.next();
        */

        /* let's try this one ... */
        for (Entry<MyClass, Vector<MyClass>> entry : classCompositions.entrySet()) {
            // get the actual class ...
            MyClass thisClass = entry.getKey();
            if (thisClass.isDisplayUML()) {
                Vector<MyClass> otherClasses = classCompositions.get(thisClass);
                for (MyClass otherClass : otherClasses)
                    drawComposition(g, thisClass, otherClass, classUsings);
            }
        }
    }

    if (isShowAggregation()) {
        /*Set<MyClass> set2 = classAggregations.keySet();
        Iterator<MyClass> itr2 = set2.iterator();
        while (itr2.hasNext())
        {
          MyClass thisClass = itr2.next();
        */

        /* let's try this one ... */
        for (Entry<MyClass, Vector<MyClass>> entry : classAggregations.entrySet()) {
            // get the actual class ...
            MyClass thisClass = entry.getKey();
            if (thisClass.isDisplayUML()) {
                Vector<MyClass> otherClasses = classAggregations.get(thisClass);
                for (MyClass otherClass : otherClasses)
                    drawAggregation(g, thisClass, otherClass, classUsings);
            }
        }
    }

    // draw classes again to put them on top
    // of the arrows
    /*set = classes.keySet();
    itr = set.iterator();
    while (itr.hasNext())
    {
      String str = itr.next();
    */

    /* let's try this one ... */
    for (Entry<String, MyClass> entry : classes.entrySet()) {
        // get the actual class ...
        String str = entry.getKey();

        classes.get(str).setEnabled(this.isEnabled());
        classes.get(str).draw(graphics, showFields, showMethods);

        // push outer box
        MyClass thisClass = classes.get(str);
        if (thisClass.getPosition().y < topLeft.y)
            topLeft.y = thisClass.getPosition().y;
        if (thisClass.getPosition().x < topLeft.x)
            topLeft.x = thisClass.getPosition().x;
        if (thisClass.getPosition().y + thisClass.getHeight() > bottomRight.y)
            bottomRight.y = thisClass.getPosition().y + thisClass.getHeight();
        if (thisClass.getPosition().x + thisClass.getWidth() > bottomRight.x)
            bottomRight.x = thisClass.getPosition().x + thisClass.getWidth();

    }

    // comments
    if (commentString != null) {
        String fontName = g.getFont().getName();
        g.setFont(new Font("Courier", g.getFont().getStyle(), Unimozer.DRAW_FONT_SIZE));

        if (!commentString.trim().equals("")) {
            String myCommentString = new String(commentString);
            Point myCommentPoint = new Point(commentPoint);
            //System.out.println(myCommentString);

            // adjust comment
            myCommentString = myCommentString.trim();
            // adjust position
            myCommentPoint.y = myCommentPoint.y + 16;

            // explode comment
            StringList sl = StringList.explode(myCommentString, "\n");
            // calculate totals
            int totalHeight = 0;
            int totalWidth = 0;
            for (int i = 0; i < sl.count(); i++) {
                String line = sl.get(i).trim();
                int h = (int) g.getFont().getStringBounds(line, g.getFontRenderContext()).getHeight();
                int w = (int) g.getFont().getStringBounds(line, g.getFontRenderContext()).getWidth();
                totalHeight += h;
                totalWidth = Math.max(totalWidth, w);
            }

            // get comment size
            // draw background
            g.setColor(new Color(255, 255, 128, 255));
            g.fillRoundRect(myCommentPoint.x, myCommentPoint.y, totalWidth + 8, totalHeight + 8, 4, 4);
            // draw border
            g.setColor(Color.BLACK);
            g.drawRoundRect(myCommentPoint.x, myCommentPoint.y, totalWidth + 8, totalHeight + 8, 4, 4);

            // draw text
            totalHeight = 0;
            for (int i = 0; i < sl.count(); i++) {
                String line = sl.get(i).trim();
                int h = (int) g.getFont().getStringBounds(myCommentString, g.getFontRenderContext())
                        .getHeight();
                g.drawString(line, myCommentPoint.x + 4, myCommentPoint.y + h + 2 + totalHeight);
                totalHeight += h;
            }

        }

        g.setFont(new Font(fontName, Font.PLAIN, Unimozer.DRAW_FONT_SIZE));

    }

    /*
    if(!isEnabled())
    {
        g.setColor(new Color(128,128,128,128));
        g.fillRect(0,0,getWidth(),getHeight());
            
    }
    */

    this.setPreferredSize(new Dimension(mostRight + 32, mostBottom + 32));
    // THE NEXT LINE MAKES ALL DIALOGUES DISAPEAR!!
    //this.setSize(mostRight+32, mostBottom+32);
    this.validate();
    ((JScrollPane) this.getParent().getParent()).revalidate();

    if (mode == MODE_EXTENDS && extendsFrom != null && extendsDragPoint != null) {
        graphics.setColor(Color.BLUE);
        ((Graphics2D) graphics).setStroke(new BasicStroke(2));
        drawExtends(g, new Point(extendsFrom.getPosition().x + extendsFrom.getWidth() / 2,
                extendsFrom.getPosition().y + extendsFrom.getHeight() / 2), extendsDragPoint);
        graphics.setColor(Color.BLACK);
        ((Graphics2D) graphics).setStroke(new BasicStroke(1));
    }
}

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   w  w  w  . java2s  . 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:org.objectweb.proactive.extensions.timitspmd.util.charts.renderer.HierarchicalBarRenderer.java

/**
 * Draws the bar for one item in the dataset.
 *
 * @param g2//from   w ww.  j a  v a 2 s  .  c  om
 *            the graphics device.
 * @param state
 *            the renderer state.
 * @param dataArea
 *            the plot area.
 * @param plot
 *            the plot.
 * @param domainAxis
 *            the domain (category) axis.
 * @param rangeAxis
 *            the range (value) axis.
 * @param data
 *            the data.
 * @param row
 *            the row index (zero-based).
 * @param column
 *            the column index (zero-based).
 * @param pass
 *            the pass index.
 */
@Override
public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot,
        CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset data, int row, int column, int pass) {
    // nothing is drawn for null values...
    Number dataValue = data.getValue(row, column);
    if (dataValue == null) {
        return;
    }

    // BAR X
    double rectX = domainAxis.getCategoryMiddle(column, this.getColumnCount(), dataArea,
            plot.getDomainAxisEdge()) - (state.getBarWidth() / 2.0);

    int seriesCount = this.getRowCount();

    // BAR Y
    double value = dataValue.doubleValue();
    double base = 0.0;
    double lclip = this.getLowerClip();
    double uclip = this.getUpperClip();

    if (uclip <= 0.0) { // cases 1, 2, 3 and 4
        if (value >= uclip) {
            return; // bar is not visible
        }
        base = uclip;
        if (value <= lclip) {
            value = lclip;
        }
    } else if (lclip <= 0.0) { // cases 5, 6, 7 and 8
        if (value >= uclip) {
            value = uclip;
        } else {
            if (value <= lclip) {
                value = lclip;
            }
        }
    } else { // cases 9, 10, 11 and 12
        if (value <= lclip) {
            return; // bar is not visible
        }
        base = this.getLowerClip();
        if (value >= uclip) {
            value = uclip;
        }
    }

    RectangleEdge edge = plot.getRangeAxisEdge();
    double transY1 = rangeAxis.valueToJava2D(base, dataArea, edge);
    double transY2 = rangeAxis.valueToJava2D(value, dataArea, edge);
    double rectY = Math.min(transY2, transY1);

    double rectWidth = state.getBarWidth();
    double rectHeight = Math.abs(transY2 - transY1);

    // draw the bar...
    double shift = 0.0;
    rectWidth = 0.0;
    double widthFactor = 1.0;
    double seriesBarWidth = this.getSeriesBarWidth(row);
    if (!Double.isNaN(seriesBarWidth)) {
        widthFactor = seriesBarWidth;
    }
    rectWidth = widthFactor * state.getBarWidth();
    rectX = rectX + (((1 - widthFactor) * state.getBarWidth()) / 2.0);
    if (seriesCount > 1) {
        // needs to be improved !!!
        shift = (rectWidth * 0.20) / (seriesCount - 1);
    }

    Rectangle2D bar = new Rectangle2D.Double((rectX + ((seriesCount - 1 - row) * shift)), rectY,
            (rectWidth - ((seriesCount - 1 - row) * shift * 2)), rectHeight);

    double rrX;
    double rrY;
    double rrW;
    double rrH;
    if (row == 0) {
        @SuppressWarnings("unchecked")
        Iterator it = this.datasetTree[column].getDescendants();
        int numElement = -1;
        while (it.hasNext()) {
            try {
                Element elt = (Element) it.next();
                numElement++;
                String name = elt.getAttributeValue("name");
                dataValue = Double.valueOf(elt.getAttributeValue("avg"));
                // System.out.println("["+column+"] "+name+" \t-->
                // "+dataValue);
                // BAR X
                rectX = domainAxis.getCategoryMiddle(column, this.getColumnCount(), dataArea,
                        plot.getDomainAxisEdge()) - (state.getBarWidth() / 2.0);

                seriesCount = this.getRowCount();

                // BAR Y
                value = dataValue.doubleValue();
                base = 0.0;
                lclip = this.getLowerClip();
                uclip = this.getUpperClip();

                if (uclip <= 0.0) { // cases 1, 2, 3 and 4
                    if (value >= uclip) {
                        return; // bar is not visible
                    }
                    base = uclip;
                    if (value <= lclip) {
                        value = lclip;
                    }
                } else if (lclip <= 0.0) { // cases 5, 6, 7 and 8
                    if (value >= uclip) {
                        value = uclip;
                    } else {
                        if (value <= lclip) {
                            value = lclip;
                        }
                    }
                } else { // cases 9, 10, 11 and 12
                    if (value <= lclip) {
                        return; // bar is not visible
                    }
                    base = this.getLowerClip();
                    if (value >= uclip) {
                        value = uclip;
                    }
                }

                edge = plot.getRangeAxisEdge();
                transY1 = rangeAxis.valueToJava2D(base, dataArea, edge);
                transY2 = rangeAxis.valueToJava2D(value, dataArea, edge);
                rectY = Math.min(transY2, transY1);

                rectWidth = state.getBarWidth();
                rectHeight = Math.abs(transY2 - transY1);

                // draw the bar...
                shift = 0.0;
                rectWidth = 0.0;
                widthFactor = 1.0;
                seriesBarWidth = this.getSeriesBarWidth(row);
                if (!Double.isNaN(seriesBarWidth)) {
                    widthFactor = seriesBarWidth;
                }
                rectWidth = widthFactor * state.getBarWidth();
                rectX = rectX + (((1 - widthFactor) * state.getBarWidth()) / 2.0);
                if (seriesCount > 1) {
                    // needs to be improved !!!
                    shift = (rectWidth * 0.20) / (seriesCount - 1);
                }
                rrX = (rectX + ((seriesCount - 1 - row) * shift));
                rrY = rectY;
                rrW = (rectWidth - ((seriesCount - 1 - row) * shift * 2));
                rrH = rectHeight;

                // IMPORTANT NOTE :
                // dev attribute is used to save width of the element
                // min attribute is used to save X position of the element
                // max attribute is used to save the number of child already
                // managed
                if (numElement == 0) {
                    elt.setAttribute("dev", "" + rrW);
                    elt.setAttribute("min", "" + rrX);
                    elt.setAttribute("max", "0");
                } else {
                    Element parent = elt.getParentElement();

                    // System.out.println(" Parent
                    // "+parent.getAttributeValue("name")
                    // + " rrX/rrW/child -> "
                    // + parent.getAttributeValue("min")+"/"
                    // + parent.getAttributeValue("dev")+"/"
                    // + parent.getAttributeValue("max") );
                    double pW = Double.valueOf(parent.getAttributeValue("dev"));
                    double pX = Double.valueOf(parent.getAttributeValue("min"));
                    int numChild = Integer.valueOf(parent.getAttributeValue("max"));

                    rrW = pW / parent.getChildren().size();
                    rrX = pX + (rrW * numChild);
                    rrX += HierarchicalBarRenderer.INCLUSION_MARGIN;
                    rrW -= (HierarchicalBarRenderer.INCLUSION_MARGIN * 2);
                    elt.setAttribute("dev", "" + rrW);
                    elt.setAttribute("min", "" + rrX);
                    parent.setAttribute("max", "" + (numChild + 1));
                }

                RoundRectangle2D rbar = new RoundRectangle2D.Double(rrX, rrY, rrW, rrH,
                        HierarchicalBarRenderer.CORNER, HierarchicalBarRenderer.CORNER);

                Rectangle2D childSumLine = null;
                double childSum = Double.valueOf(elt.getAttributeValue("sum"));
                transY1 = rangeAxis.valueToJava2D(base, dataArea, edge);
                transY2 = rangeAxis.valueToJava2D(childSum, dataArea, edge);
                rectY = Math.min(transY2, transY1);

                childSum = (childSum / dataValue.doubleValue()) * rrH;
                if ((childSum < rrH) && (childSum > 0) && ((childSum / rrH) < 0.95)) {
                    childSumLine = new Rectangle2D.Double(rrX, rectY, rrW, 1);
                }
                Paint itemPaint = this.getItemPaintFromName(name, this.series, column);
                GradientPaintTransformer t = this.getGradientPaintTransformer();
                if ((t != null) && itemPaint instanceof GradientPaint) {
                    itemPaint = t.transform((GradientPaint) itemPaint, bar);
                }
                g2.setPaint(itemPaint);

                Color c = g2.getColor();
                g2.setColor(new Color(c.getRed(), c.getGreen(), c.getBlue(), this.alpha));
                g2.fill(rbar);
                g2.setColor(Color.DARK_GRAY);
                if (childSumLine != null) {
                    g2.fill(childSumLine);
                }

                // draw the outline...
                if (this.isDrawBarOutline()
                        && (state.getBarWidth() > BarRenderer.BAR_OUTLINE_WIDTH_THRESHOLD)) {
                    Stroke stroke = this.getItemOutlineStroke(row, column);
                    Paint paint = this.getItemOutlinePaint(row, column);
                    if ((stroke != null) && (paint != null)) {
                        g2.setStroke(stroke);
                        g2.setPaint(paint);
                        g2.draw(rbar);
                    }
                }
            } catch (ClassCastException e) {
                continue;
            }
        }
    }

    // ////////////////////////////

    // draw the item labels if there are any...
    double transX1 = rangeAxis.valueToJava2D(base, dataArea, edge);
    double transX2 = rangeAxis.valueToJava2D(value, dataArea, edge);

    CategoryItemLabelGenerator generator = this.getItemLabelGenerator(row, column);
    if ((generator != null) && this.isItemLabelVisible(row, column)) {
        this.drawItemLabel(g2, data, row, column, plot, generator, bar, (transX1 > transX2));
    }

    // collect entity and tool tip information...
    if (state.getInfo() != null) {
        EntityCollection entities = state.getEntityCollection();
        if (entities != null) {
            String tip = null;
            CategoryToolTipGenerator tipster = this.getToolTipGenerator(row, column);
            if (tipster != null) {
                tip = tipster.generateToolTip(data, row, column);
            }
            String url = null;
            if (this.getItemURLGenerator(row, column) != null) {
                url = this.getItemURLGenerator(row, column).generateURL(data, row, column);
            }
            CategoryItemEntity entity = new CategoryItemEntity(bar, tip, url, data, row,
                    data.getColumnKey(column), column);
            entities.add(entity);
        }
    }
}