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:com.openkm.module.direct.DirectWorkflowModule.java

@Override
public byte[] getProcessDefinitionImage(String token, long processDefinitionId, String node)
        throws RepositoryException, DatabaseException, WorkflowException {
    log.debug("getProcessDefinitionImage({}, {}, {})", new Object[] { token, processDefinitionId, node });
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
    byte[] image = null;
    Session session = null;/*w  w  w .j a v a2  s .  c  o m*/

    try {
        if (token == null) {
            session = JCRUtils.getSession();
        } else {
            session = JcrSessionManager.getInstance().get(token);
        }

        GraphSession graphSession = jbpmContext.getGraphSession();
        org.jbpm.graph.def.ProcessDefinition pd = graphSession.getProcessDefinition(processDefinitionId);
        FileDefinition fileDef = pd.getFileDefinition();

        WorkflowUtils.DiagramInfo dInfo = WorkflowUtils.getDiagramInfo(fileDef.getInputStream("gpd.xml"));
        WorkflowUtils.DiagramNodeInfo dNodeInfo = dInfo.getNodeMap().get(node);
        BufferedImage img = ImageIO.read(fileDef.getInputStream("processimage.jpg"));

        // Obtain all nodes Y
        List<Integer> ordenadas = new ArrayList<Integer>();

        for (WorkflowUtils.DiagramNodeInfo nodeInfo : dInfo.getNodeMap().values()) {
            ordenadas.add(nodeInfo.getY());
        }

        // Calculate minimal Y
        Collections.sort(ordenadas);
        int fix = ordenadas.get(0);

        if (dNodeInfo != null) {
            // Select node
            log.debug("DiagramNodeInfo: {}", dNodeInfo);
            Graphics g = img.getGraphics();
            Graphics2D g2d = (Graphics2D) g;
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.25F));
            g2d.setColor(Color.blue);
            g2d.fillRect(dNodeInfo.getX(), dNodeInfo.getY() - fix, dNodeInfo.getWidth(), dNodeInfo.getHeight());
            g.dispose();
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(img, "jpg", baos);
        image = baos.toByteArray();
        baos.flush();
        baos.close();

        // Activity log
        UserActivity.log(session.getUserID(), "GET_PROCESS_DEFINITION_IMAGE", "" + processDefinitionId, null);
    } catch (javax.jcr.RepositoryException e) {
        throw new RepositoryException(e.getMessage(), e);
    } catch (JbpmException e) {
        throw new WorkflowException(e.getMessage(), e);
    } catch (IOException e) {
        throw new WorkflowException(e.getMessage(), e);
    } finally {
        if (token == null)
            JCRUtils.logout(session);
        jbpmContext.close();
    }

    log.debug("getProcessDefinitionImage: {}", image);
    return image;
}

From source file:org.sakaiproject.sitestats.impl.ServerWideReportManagerImpl.java

private byte[] generateNoDataChart(int width, int height) {
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = img.createGraphics();

    g2d.setBackground(parseColor(statsManager.getChartBackgroundColor()));
    g2d.clearRect(0, 0, width - 1, height - 1);
    g2d.setColor(parseColor("#cccccc"));
    g2d.drawRect(0, 0, width - 1, height - 1);
    Font f = new Font("SansSerif", Font.PLAIN, 12);
    g2d.setFont(f);/*from ww  w .  j  a  v  a2 s.c om*/
    FontMetrics fm = g2d.getFontMetrics(f);
    String noData = msgs.getString("no_data");
    int noDataWidth = fm.stringWidth(noData);
    int noDataHeight = fm.getHeight();
    g2d.setColor(parseColor("#555555"));
    g2d.drawString(noData, width / 2 - noDataWidth / 2, height / 2 - noDataHeight / 2 + 2);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ImageIO.write(img, "png", out);
    } catch (IOException e) {
        log.warn("Error occurred while generating SiteStats chart image data", e);
    }
    return out.toByteArray();
}

From source file:peakml.util.jfreechart.FastTimePlot.java

@Override
public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState,
        PlotRenderingInfo info) {/* w ww.  j  a  va  2 s .co m*/
    // add the plot area to the info (used amongst other by the axis for zooming)
    if (info != null)
        info.setPlotArea(area);

    // add the insets (if any)
    RectangleInsets insets = getInsets();
    insets.trim(area);

    // draw the axis and add the dataArea to the info (used amongst other by the axis for zooming)
    AxisSpace space = new AxisSpace();
    space = xaxis.reserveSpace(g2, this, area, RectangleEdge.BOTTOM, space);
    space = yaxis.reserveSpace(g2, this, area, RectangleEdge.LEFT, space);

    Rectangle2D dataArea = space.shrink(area, null);
    if (info != null)
        info.setDataArea(dataArea);

    // flood fill the whole area with the background color
    drawBackground(g2, dataArea);

    // draw the axis
    xaxis.draw(g2, dataArea.getMaxY(), area, dataArea, RectangleEdge.BOTTOM, info);
    yaxis.draw(g2, dataArea.getMinX(), area, dataArea, RectangleEdge.LEFT, info);

    // sanity check
    if (dataseries.size() == 0)
        return;

    // clip the draw area
    Shape originalclip = g2.getClip();
    g2.clip(dataArea);

    // draw all the values
    int index = 0;
    for (Data data : dataseries.values()) {
        g2.setColor(new Color(data.color == -1 ? colormap.getColor(index++) : data.color));
        for (int i = 0; i < data.size - 1; ++i) {
            g2.drawLine((int) xaxis.valueToJava2D(data.time[i], dataArea, RectangleEdge.BOTTOM),
                    (int) yaxis.valueToJava2D(data.values[i], dataArea, RectangleEdge.LEFT),
                    (int) xaxis.valueToJava2D(data.time[i + 1], dataArea, RectangleEdge.BOTTOM),
                    (int) yaxis.valueToJava2D(data.values[i + 1], dataArea, RectangleEdge.LEFT));
        }
    }

    // reset
    g2.setClip(originalclip);
}

From source file:ucar.unidata.idv.control.chart.TimeSeriesChart.java

/**
 * draw the time line/*from  ww  w. j  a va 2s.  co  m*/
 *
 * @param g2 param
 * @param plot param
 * @param dataArea param
 * @param domainAxis param
 * @param rangeAxis param
 * @param rendererIndex param
 * @param info param
 */
private void drawTime(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis,
        ValueAxis rangeAxis, int rendererIndex, PlotRenderingInfo info) {
    try {
        Animation animation = control.getSomeAnimation();
        if (animation == null) {
            return;
        }
        Real dttm = animation.getAniValue();
        if (dttm == null) {
            return;
        }
        g2.setStroke(new BasicStroke());
        g2.setColor(Color.black);
        double timeValue = dttm.getValue(CommonUnit.secondsSinceTheEpoch);
        int x = (int) domainAxis.valueToJava2D(timeValue * 1000, dataArea, RectangleEdge.BOTTOM);
        if ((x < dataArea.getX()) || (x > dataArea.getX() + dataArea.getWidth())) {
            return;
        }

        int bottom = (int) (dataArea.getY() + dataArea.getHeight());
        int top = (int) (dataArea.getY());
        int offset = 0;
        if (false && (clockImage == null)) {
            clockImage = GuiUtils.getImage("/auxdata/ui/icons/clock.gif");
            clockImage.getHeight(this);
            offset = clockImage.getHeight(null);
        }

        //            g2.drawLine(x, (int) dataArea.getY(), x, bottom - offset);
        int w = 8;
        int w2 = w / 2;
        int[] xs = { x - w2, x, x + w2, x };
        int[] ys = { top, top + w, top, top };
        //            g2.drawLine(x, top, x, top+10);
        g2.fillPolygon(xs, ys, xs.length);
        if (clockImage != null) {
            g2.drawImage(clockImage, x - clockImage.getWidth(null) / 2, bottom - clockImage.getHeight(null),
                    null);
        }
    } catch (VisADException exc) {
    } catch (RemoteException exc) {
    }
}

From source file:com.att.aro.diagnostics.GraphPanel.java

/**
 * Creating DchTail and FachTail Cross Hatch
 * /*from www.  j  a  va  2  s . c  om*/
 * @return Paint The Tail state paint object
 */
private static Paint getTailPaint(Color color) {

    BufferedImage bufferedImage = new BufferedImage(5, 5, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = bufferedImage.createGraphics();
    g2.setColor(Color.white);
    g2.fillRect(0, 0, 5, 5);
    g2.setColor(color);
    g2.drawLine(0, 0, 5, 5);
    g2.drawLine(5, 5, 0, 0);
    g2.drawLine(0, 5, 5, 0);
    Rectangle2D rect = new Rectangle2D.Double(0, 0, 5, 5);
    return new TexturePaint(bufferedImage, rect);
}

From source file:org.apache.fop.render.pcl.PCLRenderer.java

/**
 * {@inheritDoc}/*  w ww  .j  a  v  a2 s . c  o  m*/
 */
protected void renderText(final TextArea text) {
    renderInlineAreaBackAndBorders(text);

    String fontname = getInternalFontNameForArea(text);
    final int fontsize = text.getTraitAsInteger(Trait.FONT_SIZE);

    //Determine position
    int saveIP = currentIPPosition;
    final int rx = currentIPPosition + text.getBorderAndPaddingWidthStart();
    int bl = currentBPPosition + text.getOffset() + text.getBaselineOffset();

    try {

        final Color col = (Color) text.getTrait(Trait.COLOR);
        boolean pclFont = pclUtil.isAllTextAsBitmaps() ? false
                : HardcodedFonts.setFont(gen, fontname, fontsize, text.getText());
        if (pclFont) {
            //this.currentFill = col;
            if (col != null) {
                //useColor(ct);
                gen.setTransparencyMode(true, false);
                gen.selectGrayscale(col);
            }

            saveGraphicsState();
            graphicContext.translate(rx, bl);
            setCursorPos(0, 0);
            gen.setTransparencyMode(true, true);
            if (text.hasUnderline()) {
                gen.writeCommand("&d0D");
            }
            super.renderText(text); //Updates IPD and renders words and spaces
            if (text.hasUnderline()) {
                gen.writeCommand("&d@");
            }
            restoreGraphicsState();
        } else {
            //Use Java2D to paint different fonts via bitmap
            final Font font = getFontFromArea(text);
            final int baseline = text.getBaselineOffset();

            //for cursive fonts, so the text isn't clipped
            int extraWidth = font.getFontSize() / 3;
            final FontMetricsMapper mapper = (FontMetricsMapper) fontInfo.getMetricsFor(font.getFontName());
            int maxAscent = mapper.getMaxAscent(font.getFontSize()) / 1000;
            final int additionalBPD = maxAscent - baseline;

            Graphics2DAdapter g2a = getGraphics2DAdapter();
            final Rectangle paintRect = new Rectangle(rx, currentBPPosition + text.getOffset() - additionalBPD,
                    text.getIPD() + extraWidth, text.getBPD() + additionalBPD);
            RendererContext rc = createRendererContext(paintRect.x, paintRect.y, paintRect.width,
                    paintRect.height, null);
            Map atts = new java.util.HashMap();
            atts.put(ImageHandlerUtil.CONVERSION_MODE, ImageHandlerUtil.CONVERSION_MODE_BITMAP);
            atts.put(SRC_TRANSPARENCY, "true");
            rc.setProperty(RendererContextConstants.FOREIGN_ATTRIBUTES, atts);

            Graphics2DImagePainter painter = new Graphics2DImagePainter() {

                public void paint(Graphics2D g2d, Rectangle2D area) {
                    g2d.setFont(mapper.getFont(font.getFontSize()));
                    g2d.translate(0, baseline + additionalBPD);
                    g2d.scale(1000, 1000);
                    g2d.setColor(col);
                    Java2DRenderer.renderText(text, g2d, font);
                    renderTextDecoration(g2d, mapper, fontsize, text, 0, 0);
                }

                public Dimension getImageSize() {
                    return paintRect.getSize();
                }

            };
            g2a.paintImage(painter, rc, paintRect.x, paintRect.y, paintRect.width, paintRect.height);
            currentIPPosition = saveIP + text.getAllocIPD();
        }

    } catch (IOException ioe) {
        handleIOTrouble(ioe);
    }
}

From source file:it.unibo.alchemist.boundary.monitors.Generic2DDisplay.java

/**
 * Actually draws the environment on the view.
 * //from  w ww  . j  a v  a  2 s .c o  m
 * @param g
 *            {@link Graphics2D} object responsible for drawing
 */
protected final void drawEnvOnView(final Graphics2D g) {
    if (wormhole == null || !isVisible() || !isEnabled()) {
        return;
    }
    accessData();
    if (hooked.isPresent()) {
        final Position hcoor = positions.get(hooked.get());
        final Point hp = wormhole.getViewPoint(hcoor);
        if (hp.distance(getCenter()) > FREEDOM_RADIUS) {
            wormhole.setViewPosition(hp);
        }
    }
    /*
     * Compute nodes in sight and their screen position
     */
    final Map<Node<T>, Point> onView = positions.entrySet().parallelStream()
            .map(pair -> new Pair<>(pair.getKey(), wormhole.getViewPoint(pair.getValue())))
            .filter(p -> wormhole.isInsideView(p.getSecond()))
            .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
    g.setColor(Color.BLACK);
    if (obstacles != null) {
        /*
         * TODO: only draw obstacles if on view
         */
        obstacles.parallelStream().map(this::convertObstacle).forEachOrdered(g::fill);
    }
    if (paintLinks) {
        g.setColor(Color.GRAY);
        onView.keySet().parallelStream().map(neighbors::get)
                .flatMap(neigh -> neigh.getNeighbors().parallelStream()
                        .map(node -> node.compareTo(neigh.getCenter()) > 0 ? new Pair<>(neigh.getCenter(), node)
                                : new Pair<>(node, neigh.getCenter())))
                .distinct().map(
                        pair -> mapPair(pair,
                                node -> Optional.ofNullable(onView.get(node))
                                        .orElse(wormhole.getViewPoint(positions.get(node)))))
                .forEachOrdered(line -> {
                    final Point p1 = line.getFirst();
                    final Point p2 = line.getSecond();
                    g.drawLine(p1.x, p1.y, p2.x, p2.y);
                });
    }
    releaseData();
    if (isDraggingMouse && status == ViewStatus.MOVING && originPoint.isPresent() && endingPoint.isPresent()) {
        for (final Node<T> n : selectedNodes) {
            if (onView.containsKey(n)) {
                onView.put(n, new Point(onView.get(n).x + (endingPoint.get().x - originPoint.get().x),
                        onView.get(n).y + (endingPoint.get().y - originPoint.get().y)));
            }
        }
    }
    g.setColor(Color.GREEN);
    if (effectStack != null) {
        effectStack.forEach(effect -> {
            onView.entrySet().forEach(entry -> {
                final Point p = entry.getValue();
                effect.apply(g, entry.getKey(), p.x, p.y);
            });
        });
    }
    if (isCloserNodeMarked()) {
        final Optional<Map.Entry<Node<T>, Point>> closest = onView.entrySet().parallelStream()
                .min((pair1, pair2) -> {
                    final Point p1 = pair1.getValue();
                    final Point p2 = pair2.getValue();
                    final double d1 = Math.hypot(p1.x - mousex, p1.y - mousey);
                    final double d2 = Math.hypot(p2.x - mousex, p2.y - mousey);
                    return Double.compare(d1, d2);
                });
        if (closest.isPresent()) {
            nearest = closest.get().getKey();
            final int nearestx = closest.get().getValue().x;
            final int nearesty = closest.get().getValue().y;
            drawFriedEgg(g, nearestx, nearesty, Color.RED, Color.YELLOW);
        }
    } else {
        nearest = null;
    }
    if (isDraggingMouse && status == ViewStatus.SELECTING && originPoint.isPresent()
            && endingPoint.isPresent()) {
        g.setColor(Color.BLACK);
        final int x = originPoint.get().x < endingPoint.get().x ? originPoint.get().x : endingPoint.get().x;
        final int y = originPoint.get().y < endingPoint.get().y ? originPoint.get().y : endingPoint.get().y;
        final int width = Math.abs(endingPoint.get().x - originPoint.get().x);
        final int height = Math.abs(endingPoint.get().y - originPoint.get().y);
        g.drawRect(x, y, width, height);
        selectedNodes = onView.entrySet().parallelStream()
                .filter(nodes -> isInsideRectangle(nodes.getValue(), x, y, width, height))
                .map(onScreen -> onScreen.getKey()).collect(Collectors.toSet());
    }
    selectedNodes.parallelStream().map(e -> Optional.ofNullable(onView.get(e))).filter(Optional::isPresent)
            .map(Optional::get).forEachOrdered(p -> drawFriedEgg(g, p.x, p.y, Color.BLUE, Color.CYAN));
}

From source file:edu.ku.brc.ui.UIRegistry.java

/**
 * Writes a string message into the BufferedImage on GlassPane and sets the main component's visibility to false and
 * shows the GlassPane./*from  w ww  .j  a va 2s.  co m*/
 * @param msg the message
 * @param pointSize the Font point size for the message to be writen in
 */
public static GhostGlassPane writeGlassPaneMsg(final String msg, final int pointSize) {
    GhostGlassPane glassPane = getGlassPane();
    if (glassPane != null) {
        glassPane.finishDnD();
    }

    glassPane.setMaskingEvents(true);

    Component mainComp = get(MAINPANE);
    if (mainComp != null && glassPane != null) {
        JFrame frame = (JFrame) get(FRAME);
        frameRect = frame.getBounds();

        int y = 0;
        JMenuBar menuBar = null;
        Dimension size = mainComp.getSize();
        if (UIHelper.getOSType() != UIHelper.OSTYPE.MacOSX) {
            menuBar = frame.getJMenuBar();
            size.height += menuBar.getSize().height;
            y += menuBar.getSize().height;
        }
        BufferedImage buffer = getGlassPaneBufferedImage(size.width, size.height);
        Graphics2D g2 = buffer.createGraphics();
        if (menuBar != null) {
            menuBar.paint(g2);
        }
        g2.translate(0, y);
        mainComp.paint(g2);
        g2.translate(0, -y);

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(new Color(255, 255, 255, 128));
        g2.fillRect(0, 0, size.width, size.height);

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

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

        int expand = 20;
        int arc = expand * 2;
        g2.setColor(Color.WHITE);
        g2.fillRoundRect(tx - (expand / 2), ty - fm.getAscent() - (expand / 2), tw + expand, th + expand, arc,
                arc);

        g2.setColor(Color.DARK_GRAY);
        g2.drawRoundRect(tx - (expand / 2), ty - fm.getAscent() - (expand / 2), tw + expand, th + expand, arc,
                arc);

        g2.setColor(Color.BLACK);
        g2.drawString(msg, tx, ty);
        g2.dispose();

        glassPane.setImage(buffer);
        glassPane.setPoint(new Point(0, 0), GhostGlassPane.ImagePaintMode.ABSOLUTE);
        glassPane.setOffset(new Point(0, 0));

        glassPane.setVisible(true);
        mainComp.setVisible(false);

        //Using paintImmediately fixes problems with glass pane not showing, such as for workbench saves initialed
        //during workbench or app shutdown. Don't know if there is a better way to fix it.
        //glassPane.repaint();
        glassPane.paintImmediately(glassPane.getBounds());
        showingGlassPane = true;
    }

    return glassPane;
}

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

@Override
protected void paintLayer(Graphics2D g2, JXLayer<? extends V> layer) {
    super.paintLayer(g2, layer);

    final ChartPanel chartPanel = ((ChartPanel) layer.getView());

    final Rectangle2D _plotArea = chartPanel.getChartRenderingInfo().getPlotInfo().getDataArea();

    this.drawArea.setRect(_plotArea);

    if (false == this.investmentFlowChartJDialog.isFinishLookUpPrice()) {
        this.drawBusyBox(g2, layer);
    }//from  ww  w .ja  v  a2s.  co m

    if (this.investPoint != null) {
        final int RADIUS = 8;
        final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
        final Color oldColor = g2.getColor();

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(COLOR_RED);
        g2.fillOval((int) (this.investPoint.getX() - (RADIUS >> 1) + 0.5),
                (int) (this.investPoint.getY() - (RADIUS >> 1) + 0.5), RADIUS, RADIUS);
        g2.setColor(oldColor);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias);
        this.updateInvestInformationBox(g2);
    }

    if (this.ROIPoint != null) {
        final int RADIUS = 8;
        final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
        final Color oldColor = g2.getColor();

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(COLOR_BLUE);
        g2.fillOval((int) (this.ROIPoint.getX() - (RADIUS >> 1) + 0.5),
                (int) (this.ROIPoint.getY() - (RADIUS >> 1) + 0.5), RADIUS, RADIUS);
        g2.setColor(oldColor);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias);
        this.updateROIInformationBox(g2);
    }

    this.solveConflict();

    if (this.investPoint != null) {
        this.drawInformationBox(g2, this.investmentFlowChartJDialog.getInvestActivities(this.investPointIndex),
                investRect, investParams, investValues,
                GUIBundle.getString("InvestmentFlowLayerUI_Total_Invest"), totalInvestValue,
                COLOR_RED_BACKGROUND, COLOR_RED_BORDER);
    }

    if (this.ROIPoint != null) {
        this.drawInformationBox(g2, this.investmentFlowChartJDialog.getROIActivities(this.ROIPointIndex),
                ROIRect, ROIParams, ROIValues, GUIBundle.getString("InvestmentFlowLayerUI_Total_Return"),
                totalROIValue, COLOR_BLUE_BACKGROUND, COLOR_BLUE_BORDER);
    }

    this.drawTitle(g2);
}

From source file:lcmc.common.ui.ResourceGraph.java

/** Draws text on the vertex. */
private void drawVertexText(final Graphics2D g2d, final TextLayout textLayout, final double x, final double y,
        final Color color, final int alpha) {
    if (color != null) {
        g2d.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha));
    }/*from w w  w . ja  v a2 s.co  m*/
    textLayout.draw(g2d, (float) x, (float) y);
}