Example usage for java.awt AlphaComposite getInstance

List of usage examples for java.awt AlphaComposite getInstance

Introduction

In this page you can find the example usage for java.awt AlphaComposite getInstance.

Prototype

public static AlphaComposite getInstance(int rule, float alpha) 

Source Link

Document

Creates an AlphaComposite object with the specified rule and the constant alpha to multiply with the alpha of the source.

Usage

From source file:spinworld.gui.RadarPlot.java

/**
 * Draws the plot on a Java 2D graphics device (such as the screen or a
 * printer)./*from   ww  w  .j  av a 2s. c  om*/
 *
 * @param g2  the graphics device.
 * @param area  the area within which the plot should be drawn.
 * @param anchor  the anchor point (<code>null</code> permitted).
 * @param parentState  the state from the parent plot, if there is one.
 * @param info  collects info about the drawing.
 */
public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState,
        PlotRenderingInfo info) {

    // adjust for insets...
    RectangleInsets insets = getInsets();
    insets.trim(area);

    if (info != null) {
        info.setPlotArea(area);
        info.setDataArea(area);
    }

    drawBackground(g2, area);
    drawOutline(g2, area);

    Shape savedClip = g2.getClip();

    g2.clip(area);
    Composite originalComposite = g2.getComposite();
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha()));

    if (!DatasetUtilities.isEmptyOrNull(this.dataset)) {
        int seriesCount = 0, catCount = 0;

        if (this.dataExtractOrder == TableOrder.BY_ROW) {
            seriesCount = this.dataset.getRowCount();
            catCount = this.dataset.getColumnCount();
        } else {
            seriesCount = this.dataset.getColumnCount();
            catCount = this.dataset.getRowCount();
        }

        // ensure we have origin and maximum value for each axis
        ensureBoundaryValues(seriesCount, catCount);

        // Next, setup the plot area

        // adjust the plot area by the interior spacing value

        double gapHorizontal = area.getWidth() * getInteriorGap();
        double gapVertical = area.getHeight() * getInteriorGap();

        double X = area.getX() + gapHorizontal / 2;
        double Y = area.getY() + gapVertical / 2;
        double W = area.getWidth() - gapHorizontal;
        double H = area.getHeight() - gapVertical;

        double headW = area.getWidth() * this.headPercent;
        double headH = area.getHeight() * this.headPercent;

        // make the chart area a square
        double min = Math.min(W, H) / 2;
        X = (X + X + W) / 2 - min;
        Y = (Y + Y + H) / 2 - min;
        W = 2 * min;
        H = 2 * min;

        Point2D centre = new Point2D.Double(X + W / 2, Y + H / 2);
        Rectangle2D radarArea = new Rectangle2D.Double(X, Y, W, H);

        // draw the axis and category label
        for (int cat = 0; cat < catCount; cat++) {
            double angle = getStartAngle() + (getDirection().getFactor() * cat * 360 / catCount);

            Point2D endPoint = getWebPoint(radarArea, angle, 1);
            // 1 = end of axis
            Line2D line = new Line2D.Double(centre, endPoint);
            g2.setPaint(this.axisLinePaint);
            g2.setStroke(this.axisLineStroke);
            g2.draw(line);
            if (isAxisTickVisible()) {
                drawTicks(g2, radarArea, angle, cat);
            }
            drawLabel(g2, area, radarArea, 0.0, cat, angle, 360.0 / catCount);
        }

        // Now actually plot each of the series polygons..
        for (int series = 0; series < seriesCount; series++) {
            drawRadarPoly(g2, radarArea, centre, info, series, catCount, headH, headW);
        }
    } else {
        drawNoDataMessage(g2, area);
    }
    g2.setClip(savedClip);
    g2.setComposite(originalComposite);
    drawOutline(g2, area);
}

From source file:genlab.gui.jfreechart.EnhancedSpiderWebPlot.java

/**
 * Draws a radar plot polygon.//from   www. j ava 2  s . c  om
 *
 * @param g2 the graphics device.
 * @param plotArea the area we are plotting in (already adjusted).
 * @param centre the centre point of the radar axes
 * @param info chart rendering info.
 * @param series the series within the dataset we are plotting
 * @param catCount the number of categories per radar plot
 * @param headH the data point height
 * @param headW the data point width
 */
protected void drawRadarPoly(Graphics2D g2, Rectangle2D plotArea, Point2D centre, PlotRenderingInfo info,
        int series, int catCount, double headH, double headW) {

    Polygon polygon = new Polygon();

    EntityCollection entities = null;
    if (info != null) {
        entities = info.getOwner().getEntityCollection();
    }

    // plot the data...
    for (int cat = 0; cat < catCount; cat++) {

        Number dataValue = getPlotValue(series, cat);

        if (dataValue != null) {
            double value = dataValue.doubleValue();

            if (value >= 0) { // draw the polygon series...

                // Finds our starting angle from the centre for this axis

                double angle = getStartAngle()
                        + (getDirection().getFactor() * cat * 360 / (catCount > 2 ? catCount : 3));

                // The following angle calc will ensure there isn't a top
                // vertical axis - this may be useful if you don't want any
                // given criteria to 'appear' move important than the
                // others..
                //  + (getDirection().getFactor()
                //        * (cat + 0.5) * 360 / catCount);

                // find the point at the appropriate distance end point
                // along the axis/angle identified above and add it to the
                // polygon

                Point2D point = getWebPoint(plotArea, angle, value / this.maxValue);
                polygon.addPoint((int) point.getX(), (int) point.getY());

                // put an elipse at the point being plotted..

                Paint paint = getSeriesPaint(series);
                Paint outlinePaint = getSeriesOutlinePaint(series);
                Stroke outlineStroke = getSeriesOutlineStroke(series);

                Ellipse2D head = new Ellipse2D.Double(point.getX() - headW / 2, point.getY() - headH / 2, headW,
                        headH);
                g2.setPaint(paint);
                g2.fill(head);
                g2.setStroke(outlineStroke);
                g2.setPaint(outlinePaint);
                g2.draw(head);

                if (entities != null) {
                    int row = 0;
                    int col = 0;
                    if (this.dataExtractOrder == TableOrder.BY_ROW) {
                        row = series;
                        col = cat;
                    } else {
                        row = cat;
                        col = series;
                    }
                    String tip = null;
                    if (this.toolTipGenerator != null) {
                        tip = this.toolTipGenerator.generateToolTip(this.dataset, row, col);
                    }

                    String url = null;
                    if (this.urlGenerator != null) {
                        url = this.urlGenerator.generateURL(this.dataset, row, col);
                    }

                    Shape area = new Rectangle((int) (point.getX() - headW), (int) (point.getY() - headH),
                            (int) (headW * 2), (int) (headH * 2));
                    CategoryItemEntity entity = new CategoryItemEntity(area, tip, url, this.dataset,
                            this.dataset.getRowKey(row), this.dataset.getColumnKey(col));
                    entities.add(entity);
                }

            }
        }
    }
    // Plot the polygon

    Paint paint = getSeriesPaint(series);
    g2.setPaint(paint);
    g2.setStroke(getSeriesOutlineStroke(series));
    g2.draw(polygon);

    // Lastly, fill the web polygon if this is required

    if (this.webFilled) {
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f));
        g2.fill(polygon);
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha()));
    }
}

From source file:genlab.gui.jfreechart.EnhancedSpiderWebPlot.java

/**
 * Draws the label for one axis.// w ww  . j ava 2s  . c  o  m
 *
 * @param g2  the graphics device.
 * @param plotArea  the plot area
 * @param value  the value of the label (ignored).
 * @param cat  the category (zero-based index).
 * @param startAngle  the starting angle.
 * @param extent  the extent of the arc.
 */
protected void drawLabel(Graphics2D g2, Rectangle2D plotArea, double value, int cat, double startAngle,
        double extent) {
    FontRenderContext frc = g2.getFontRenderContext();

    String label = null;
    if (this.dataExtractOrder == TableOrder.BY_ROW) {
        // if series are in rows, then the categories are the column keys
        label = this.labelGenerator.generateColumnLabel(this.dataset, cat);
    } else {
        // if series are in columns, then the categories are the row keys
        label = this.labelGenerator.generateRowLabel(this.dataset, cat);
    }

    Rectangle2D labelBounds = getLabelFont().getStringBounds(label, frc);
    LineMetrics lm = getLabelFont().getLineMetrics(label, frc);
    double ascent = lm.getAscent();

    Point2D labelLocation = calculateLabelLocation(labelBounds, ascent, plotArea, startAngle);

    Composite saveComposite = g2.getComposite();

    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
    g2.setPaint(getLabelPaint());
    g2.setFont(getLabelFont());
    g2.drawString(label, (float) labelLocation.getX(), (float) labelLocation.getY());
    g2.setComposite(saveComposite);
}

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

/**
 * Draws the labels for each dataset ID, returning the x coordinate for
 * subsequent drawing for each row.//from   w w  w .  jav  a  2 s  .co m
 *
 * @param g2
 * @param offset
 * @param separation
 * @param multiGenomeAlignmentSummaries
 * @return
 */
private int drawLabels(Graphics2D g2, int offset, int separation,
        Collection<MultiGenomeAlignmentSummary> multiGenomeAlignmentSummaries) {
    int n = multiGenomeAlignmentSummaries.size();
    boolean drawNumbers = false;
    if (n > 1) {
        int i = 0;
        for (MultiGenomeAlignmentSummary multiGenomeAlignmentSummary : multiGenomeAlignmentSummaries) {
            i++;
            String datasetId = multiGenomeAlignmentSummary.getDatasetId();
            String datasetDisplayLabel = datasetDisplayLabels.get(datasetId);
            if (!Integer.toString(i).equals(datasetDisplayLabel)) {
                drawNumbers = true;
                break;
            }
        }
    }
    int x = gapSize;
    int y = offset;
    int maxWidth = 0;
    if (drawNumbers) {
        for (int i = 1; i <= n; i++) {
            String s = Integer.toString(i) + ".";
            g2.drawString(s, x, y);
            maxWidth = Math.max(maxWidth, g2.getFontMetrics().stringWidth(s));
            y += separation;
        }
        x += maxWidth + gapSize / 2;
    }
    y = offset;
    maxWidth = 0;
    for (MultiGenomeAlignmentSummary multiGenomeAlignmentSummary : multiGenomeAlignmentSummaries) {
        String datasetId = multiGenomeAlignmentSummary.getDatasetId();
        String datasetDisplayLabel = datasetDisplayLabels.get(datasetId);
        g2.drawString(datasetDisplayLabel, x, y);
        maxWidth = Math.max(maxWidth, g2.getFontMetrics().stringWidth(datasetDisplayLabel));
        y += separation;
    }
    int acceptableWidth = (int) (0.15 * plotWidth);
    if (maxWidth > acceptableWidth) {
        Composite origComposite = g2.getComposite();
        y = offset - g2.getFontMetrics().getHeight() - separation / 4;
        for (int i = 0; i < n; i++) {
            g2.setColor(Color.WHITE);
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f));
            g2.fillRect(x + acceptableWidth, y, gapSize, separation);
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
            g2.fillRect(x + acceptableWidth + gapSize, y, plotWidth - x - acceptableWidth - gapSize,
                    separation);
            y += separation;
        }
        maxWidth = acceptableWidth;
        g2.setComposite(origComposite);
    }
    return x + maxWidth + gapSize;
}

From source file:spinworld.gui.RadarPlot.java

/**
 * Draws a radar plot polygon.//from w w w .jav  a  2  s.  co m
 *
 * @param g2 the graphics device.
 * @param plotArea the area we are plotting in (already adjusted).
 * @param centre the centre point of the radar axes
 * @param info chart rendering info.
 * @param series the series within the dataset we are plotting
 * @param catCount the number of categories per radar plot
 * @param headH the data point height
 * @param headW the data point width
 */
protected void drawRadarPoly(Graphics2D g2, Rectangle2D plotArea, Point2D centre, PlotRenderingInfo info,
        int series, int catCount, double headH, double headW) {

    Polygon polygon = new Polygon();

    EntityCollection entities = null;
    if (info != null) {
        entities = info.getOwner().getEntityCollection();
    }

    // plot the data...
    for (int cat = 0; cat < catCount; cat++) {

        Number dataValue = getPlotValue(series, cat);

        if (dataValue != null) {
            double value = dataValue.doubleValue();

            // Finds our starting angle from the centre for this axis

            double angle = getStartAngle() + (getDirection().getFactor() * cat * 360 / catCount);

            // The following angle calc will ensure there isn't a top
            // vertical axis - this may be useful if you don't want any
            // given criteria to 'appear' move important than the
            // others..
            //  + (getDirection().getFactor()
            //        * (cat + 0.5) * 360 / catCount);

            // find the point at the appropriate distance end point
            // along the axis/angle identified above and add it to the
            // polygon

            double _maxValue = getMaxValue(cat).doubleValue();
            double _origin = getOrigin(cat).doubleValue();
            double lowerBound = Math.min(_origin, _maxValue);
            double upperBound = Math.max(_origin, _maxValue);
            boolean lesser = value < lowerBound;
            boolean greater = value > upperBound;
            if ((lesser || greater) && !drawOutOfRangePoints) {
                continue;
            }
            if (lesser) {
                value = lowerBound;
            }
            if (greater) {
                value = upperBound;
            }
            double length = _maxValue == _origin ? 0 : (value - lowerBound) / (upperBound - lowerBound);
            if (_maxValue < _origin) { // inversed
                length = 1 - length;
            }
            Point2D point = getWebPoint(plotArea, angle, length);
            polygon.addPoint((int) point.getX(), (int) point.getY());

            Paint paint = getSeriesPaint(series);
            Paint outlinePaint = getSeriesOutlinePaint(series);

            double px = point.getX();
            double py = point.getY();
            g2.setPaint(paint);
            if (lesser || greater) {
                // user crosshair for out-of-range data points distinguish
                g2.setStroke(new BasicStroke(1.5f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL));
                double delta = 3;
                g2.draw(new Line2D.Double(px - delta, py, px + delta, py));
                g2.draw(new Line2D.Double(px, py - delta, px, py + delta));
            } else {
                // put an elipse at the point being plotted..
                Ellipse2D head = new Ellipse2D.Double(px - headW / 2, py - headH / 2, headW, headH);
                g2.fill(head);
                g2.setStroke(getHeadOutlineStroke(series));
                g2.setPaint(outlinePaint);
                g2.draw(head);
            }

            if (entities != null) {
                int row = 0;
                int col = 0;
                if (this.dataExtractOrder == TableOrder.BY_ROW) {
                    row = series;
                    col = cat;
                } else {
                    row = cat;
                    col = series;
                }
                String tip = null;
                if (this.toolTipGenerator != null) {
                    tip = this.toolTipGenerator.generateToolTip(this.dataset, row, col);
                }

                String url = null;
                if (this.urlGenerator != null) {
                    url = this.urlGenerator.generateURL(this.dataset, row, col);
                }

                Shape area = new Rectangle((int) (point.getX() - headW), (int) (point.getY() - headH),
                        (int) (headW * 2), (int) (headH * 2));
                CategoryItemEntity entity = new CategoryItemEntity(area, tip, url, this.dataset,
                        this.dataset.getRowKey(row), this.dataset.getColumnKey(col));
                entities.add(entity);
            }
        }
    }
    // Plot the polygon

    Paint paint = getSeriesPaint(series);
    g2.setPaint(paint);
    g2.setStroke(getSeriesOutlineStroke(series));
    g2.draw(polygon);

    // Lastly, fill the web polygon if this is required

    if (this.webFilled) {
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f));
        g2.fill(polygon);
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha()));
    }
}

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./*from  w  ww  .j  a v a2s . c o m*/
 *
 * @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:spinworld.gui.RadarPlot.java

/**
 * Draws the label for one axis./*from  w  w w . j  av  a2s.  c o  m*/
 *
 * @param g2  the graphics device.
 * @param plotArea  whole plot drawing area (e.g. including space for labels)
 * @param plotDrawingArea  the plot drawing area (just spanning of axis)
 * @param value  the value of the label (ignored).
 * @param cat  the category (zero-based index).
 * @param startAngle  the starting angle.
 * @param extent  the extent of the arc.
 */
protected void drawLabel(Graphics2D g2, Rectangle2D plotArea, Rectangle2D plotDrawingArea, double value,
        int cat, double startAngle, double extent) {
    FontRenderContext frc = g2.getFontRenderContext();

    String label = null;
    if (this.dataExtractOrder == TableOrder.BY_ROW) {
        // if series are in rows, then the categories are the column keys
        label = this.labelGenerator.generateColumnLabel(this.dataset, cat);
    } else {
        // if series are in columns, then the categories are the row keys
        label = this.labelGenerator.generateRowLabel(this.dataset, cat);
    }

    double angle = normalize(startAngle);

    Font font = getLabelFont();
    Point2D labelLocation;
    do {
        Rectangle2D labelBounds = font.getStringBounds(label, frc);
        LineMetrics lm = font.getLineMetrics(label, frc);
        double ascent = lm.getAscent();

        labelLocation = calculateLabelLocation(labelBounds, ascent, plotDrawingArea, startAngle);

        boolean leftOut = angle > 90 && angle < 270 && labelLocation.getX() < plotArea.getX();
        boolean rightOut = (angle < 90 || angle > 270)
                && labelLocation.getX() + labelBounds.getWidth() > plotArea.getX() + plotArea.getWidth();

        if (leftOut || rightOut) {
            font = font.deriveFont(font.getSize2D() - 1);
        } else {
            break;
        }
    } while (font.getSize() > 8);

    Composite saveComposite = g2.getComposite();

    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
    g2.setPaint(getLabelPaint());
    g2.setFont(font);
    g2.drawString(label, (float) labelLocation.getX(), (float) labelLocation.getY());
    g2.setComposite(saveComposite);
}

From source file:lucee.runtime.img.Image.java

public void setAlpha(float alpha) throws ExpressionException {
    this.alpha = alpha;
    Graphics2D g = getGraphics();

    Composite alphaComposite;/*w w  w  .  jav  a  2  s .co m*/
    if (composite == null) {
        if (alpha == 1)
            return;
        composite = g.getComposite();
    }
    if (alpha == 1)
        alphaComposite = composite;
    else
        alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);

    g.setComposite(alphaComposite);
    //graphics.setComposite(originalComposite);   
}

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);/* ww w . j  a v 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.pmedv.blackboard.components.BoardEditor.java

/**
 * Draws the selected item to the graphics context
 * /*w  w  w  . j a v  a  2s  .  c  om*/
 * @param layer the layer to be drawn
 * @param g2d the graphics context
 */
private void drawLayer(Layer layer, Graphics2D g2d) {
    if (!layer.isVisible())
        return;

    DefaultTransformModel xmodel = null;

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

    if (layer.getName().equalsIgnoreCase("board")) {
        if (backgroundImage != null) {
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, layer.getOpacity()));
            g2d.drawImage(backgroundImage, 0, 0, this);
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
        } else {
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, getWidth(), getHeight());
        }

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

        Boolean dotGrid = (Boolean) Preferences.values
                .get("org.pmedv.blackboard.BoardDesignerPerspective.dotGrid");
        // draw grid
        if (gridVisible) {
            BoardUtil.drawGrid(g2d, raster, model.getWidth(), model.getHeight(), dotGrid.booleanValue());
        }

        return;
    }

    if (layer.getName().equalsIgnoreCase("ratsnest")) {
        if (layer.getImage() != null) {
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, layer.getOpacity()));
            g2d.drawImage(layer.getImage(), 0, 0, this);
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
        }
        return;
    }

    for (Item item : layer.getItems()) {

        if (xmodel != null)
            item.setMirror(xmodel.isMirror());

        item.setOpacity(layer.getOpacity());

        if (item instanceof Line) {
            Line line = (Line) item;
            if (line.getStroke() != null)
                g2d.setStroke(line.getStroke());
            else
                g2d.setStroke(BoardUtil.stroke_3_0f);
            g2d.setColor(item.getColor());
        }

        item.draw(g2d);

        if (selectedItems.contains(item)) {
            g2d.setColor(Color.GREEN);
            g2d.setStroke(BoardUtil.stroke_1_0f);
            item.drawHandles(g2d, 8);
        }
    }
}