Example usage for java.awt BasicStroke CAP_ROUND

List of usage examples for java.awt BasicStroke CAP_ROUND

Introduction

In this page you can find the example usage for java.awt BasicStroke CAP_ROUND.

Prototype

int CAP_ROUND

To view the source code for java.awt BasicStroke CAP_ROUND.

Click Source Link

Document

Ends unclosed subpaths and dash segments with a round decoration that has a radius equal to half of the width of the pen.

Usage

From source file:org.eclipse.smarthome.ui.internal.chart.defaultchartprovider.DefaultChartProvider.java

boolean addItem(Chart chart, QueryablePersistenceService service, Date timeBegin, Date timeEnd, Item item,
        int seriesCounter, ChartTheme chartTheme, int dpi) {
    Color color = chartTheme.getLineColor(seriesCounter);

    // Get the item label
    String label = null;//from w w w.  j a  va  2s  .  c om
    if (itemUIRegistry != null) {
        // Get the item label
        label = itemUIRegistry.getLabel(item.getName());
        if (label != null && label.contains("[") && label.contains("]")) {
            label = label.substring(0, label.indexOf('['));
        }
    }
    if (label == null) {
        label = item.getName();
    }

    Iterable<HistoricItem> result;
    FilterCriteria filter;

    // Generate data collections
    List<Date> xData = new ArrayList<Date>();
    List<Number> yData = new ArrayList<Number>();

    // Declare state here so it will hold the last value at the end of the process
    State state = null;

    // First, get the value at the start time.
    // This is necessary for values that don't change often otherwise data will start
    // after the start of the graph (or not at all if there's no change during the graph period)
    filter = new FilterCriteria();
    filter.setEndDate(ZonedDateTime.ofInstant(timeBegin.toInstant(), timeZoneProvider.getTimeZone()));
    filter.setItemName(item.getName());
    filter.setPageSize(1);
    filter.setOrdering(Ordering.DESCENDING);
    result = service.query(filter);
    if (result.iterator().hasNext()) {
        HistoricItem historicItem = result.iterator().next();

        state = historicItem.getState();
        xData.add(timeBegin);
        yData.add(convertData(state));
    }

    // Now, get all the data between the start and end time
    filter.setBeginDate(ZonedDateTime.ofInstant(timeBegin.toInstant(), timeZoneProvider.getTimeZone()));
    filter.setEndDate(ZonedDateTime.ofInstant(timeEnd.toInstant(), timeZoneProvider.getTimeZone()));
    filter.setPageSize(Integer.MAX_VALUE);
    filter.setOrdering(Ordering.ASCENDING);

    // Get the data from the persistence store
    result = service.query(filter);
    Iterator<HistoricItem> it = result.iterator();

    // Iterate through the data
    while (it.hasNext()) {
        HistoricItem historicItem = it.next();

        // For 'binary' states, we need to replicate the data
        // to avoid diagonal lines
        if (state instanceof OnOffType || state instanceof OpenClosedType) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(historicItem.getTimestamp());
            cal.add(Calendar.MILLISECOND, -1);
            xData.add(cal.getTime());
            yData.add(convertData(state));
        }

        state = historicItem.getState();
        xData.add(historicItem.getTimestamp());
        yData.add(convertData(state));
    }

    // Lastly, add the final state at the endtime
    if (state != null) {
        xData.add(timeEnd);
        yData.add(convertData(state));
    }

    // Add the new series to the chart - only if there's data elements to display
    // The chart engine will throw an exception if there's no data
    if (xData.size() == 0) {
        return false;
    }

    // If there's only 1 data point, plot it again!
    if (xData.size() == 1) {
        xData.add(xData.iterator().next());
        yData.add(yData.iterator().next());
    }

    Series series = chart.addSeries(label, xData, yData);
    float lineWidth = (float) chartTheme.getLineWidth(dpi);
    series.setLineStyle(new BasicStroke(lineWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER));
    series.setMarker(SeriesMarker.NONE);
    series.setLineColor(color);

    // If the start value is below the median, then count legend position down
    // Otherwise count up.
    // We use this to decide whether to put the legend in the top or bottom corner.
    if (yData.iterator().next().floatValue() > ((series.getYMax() - series.getYMin()) / 2 + series.getYMin())) {
        legendPosition++;
    } else {
        legendPosition--;
    }

    return true;
}

From source file:org.global.canvas.services.impl.DrawServiceImpl.java

public void draw(DrawEvent event) {
    currentUser = event.getUser();/*from www.  jav  a  2  s .  c o m*/
    if (event.getType().equals("dragstart")) {
        domImpl = GenericDOMImplementation.getDOMImplementation();
        document = domImpl.createDocument(svgNS, "svg", null);
        svgGenerator = new SVGGraphics2D(document);
        System.out.println("Color here: " + event.getColor());
        svgGenerator.setColor(Color.decode(event.getColor()));
        svgGenerator.setStroke(
                new BasicStroke(5, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL, 0, new float[] { 3, 1 }, 0));
    }

    currentX.add(event.getX());
    currentY.add(event.getY());

    if (event.getType().equals("dragend")) {
        svgGenerator.drawPolyline(ArrayUtils.toPrimitive(currentX.toArray(new Integer[0])),
                ArrayUtils.toPrimitive(currentY.toArray(new Integer[0])), currentX.size());
        export();
        domImpl = null;
        document = null;
        svgGenerator = null;
        currentX.clear();
        currentY.clear();

    }

}

From source file:org.jcurl.demo.tactics.CurveShapeDemo.java

public static void main(String[] args) {
    log.info("Version: " + Version.find());
    final R1RNFunction c;
    {/*  ww  w . j  a v  a2  s  .c om*/
        final R1R1Function[] f = new R1R1Function[2];
        final double[] fx = { 200, 150 };
        final double[] fy = { 4, 4, 4, 4, 4 };
        f[0] = new Polynome(fx);
        f[1] = new Polynome(fy);
        c = new CurveFkt(f);
    }
    final CurveShapeDemo frame = new CurveShapeDemo(c);
    frame.setSize(500, 400);
    frame.setVisible(true);
    frame.setContentPane(new JPanel() {

        private static final long serialVersionUID = -3582299332757831635L;

        private final double[] sections = new double[10];

        final Stroke st = new BasicStroke(20, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0);

        public void paintComponent(Graphics g) {
            setBackground(new Color(255, 255, 255));
            super.paintComponent(g);
            setBackground(new Color(255, 255, 255));
            final Graphics2D g2 = (Graphics2D) g;
            g2.scale(0.75, 0.75);
            g2.setPaint(new Color(0, 0, 255));
            g2.setStroke(st);
            g2.drawLine(0, 0, 650, 500);
            g2.setPaint(new Color(255, 170, 0, 128));
            // FIXME g2.draw(CurveShape.approximate(frame.curve, CurveShape.sections(-1, 3, sections)));
        }
    });
}

From source file:org.jcurl.demo.tactics.sg.BroomPromptScenario.java

public BroomPromptScenario() {
    // create the scene
    final boolean stickUp = false;
    final boolean bothSides = true;
    final int pieAngle = 150;
    final Color sp = Color.BLACK;
    final Color bgc = new Color(1, 1, 1, 0.5f);
    final Stroke fine = new BasicStroke(0.01f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
    final Stroke bold = new BasicStroke(0.03f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
    // final Font fo = new Font("SansSerif", Font.BOLD, 1);
    final float halo = RockProps.DEFAULT.getRadius();
    final float outer = 0.8f * RockProps.DEFAULT.getRadius();
    stickLength = (stickUp ? 1 : -1) * 5 * outer;
    final float inner = 0.5F * outer;

    final SGGroup me = new SGGroup();
    // the transparent background
    {// www  . j a v  a  2s  .  c  o m
        final SGShape bg = node(new Arc2D.Float(-halo, -halo, 2 * halo, 2 * halo, 0, 360, Arc2D.OPEN), null,
                null, scale0);
        bg.setFillPaint(bgc);
        bg.addMouseListener(new MoveHandler());
        bg.setMouseBlocker(true);
        bg.setCursor(moveC);
        me.add(bg);
    }
    // the cross-hair and stick
    {
        final int off = 90;
        final int pieOff = 180;
        final int arrowLengthDegrees = 7;
        // colored pie:
        pie = node(new Arc2D.Float(-outer, -outer, 2 * outer, 2 * outer, off - pieOff, pieAngle, Arc2D.PIE),
                null, null, scale0);
        me.add(pie);
        // inner circle:
        me.add(node(new Arc2D.Float(-inner, -inner, 2 * inner, 2 * inner, off, pieOff + pieAngle, Arc2D.OPEN),
                fine, sp, scale50));
        // outer circle:
        me.add(node(new Arc2D.Float(-outer, -outer, 2 * outer, 2 * outer, off,
                pieOff + pieAngle - (14 + arrowLengthDegrees), Arc2D.OPEN), fine, sp, scale50));
        // Semantic zooming: me.add(node(new Arc2D.Float(-outer, -outer, 2 *
        // outer, 2 * outer,
        // off, pieOff + pieAngle, Arc2D.OPEN), fine, sp, -scale50));
        final double ar = Math.PI * (off + pieAngle) / 180.0;
        // radius
        // if (pieAngle % 90 != 0)
        me.add(node(new Line2D.Double(0, 0, -outer * Math.cos(ar), outer * Math.sin(ar)), bold, sp, scale0));

        // arrow:
        final float f = outer / 10;
        final SGShape s = node(IceShapes.createArrowHead(f, 3 * f, 0.5f * f), null, null, scale50);
        s.setFillPaint(sp);
        final double a = Math.PI * (off + pieAngle - arrowLengthDegrees) / 180.0;
        final AffineTransform a_ = new AffineTransform();
        a_.translate(-outer * Math.cos(a), outer * Math.sin(a));
        a_.rotate(Math.PI * (90 - (off + pieAngle) + 8 + arrowLengthDegrees) / 180.0);
        final Affine s_ = SGTransform.createAffine(a_, s);
        me.add(s_);
    }
    { // y-axis:
        me.add(node(new Line2D.Float(0, -Math.signum(stickLength) * halo, 0, stickLength), fine, sp, scale0));
        // x-axis:
        me.add(node(new Line2D.Float(-halo, 0, halo, 0), fine, sp, scale0));
    }
    { // slider
        sli = new SGShape();
        sli.setShape(IceShapes.createSlider(0.4f * outer, bothSides));
        // sli.setFillPaint(sp);
        sli.setDrawStroke(fine);
        sli.setDrawPaint(sp);
        sli.setMode(Mode.STROKE_FILL);
        sli.setAntialiasingHint(RenderingHints.VALUE_ANTIALIAS_ON);
        me.add(slider = SGTransform.createAffine(new AffineTransform(), sli));
        slider.setCursor(moveC);
        slider.addMouseListener(new SpeedHandler());
        slider.setMouseBlocker(true);
    }
    handle = SGTransform.createAffine(new AffineTransform(), me);
    scene = SGTransform.createAffine(new AffineTransform(), handle);
    scene.setVisible(false);
}

From source file:org.jcurl.zui.piccolo.BroomPromptSimple.java

public BroomPromptSimple() {
    final boolean stickUp = false;
    final boolean bothSides = true;
    final int pieAngle = 150;
    final Color sp = Color.BLACK;
    final Color bgc = new Color(1, 1, 1, 0.5f);
    final Stroke fine = new BasicStroke(0.01f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
    final Stroke bold = new BasicStroke(0.03f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
    // final Font fo = new Font("SansSerif", Font.BOLD, 1);
    final float halo = RockProps.DEFAULT.getRadius();
    final float outer = 0.8f * RockProps.DEFAULT.getRadius();
    stickLength = (stickUp ? 1 : -1) * 5 * outer;
    final float inner = 0.5F * outer;
    setPickable(false);//from w ww.ja  va2 s .  c om
    final BroomPromptSimple self = this;
    handle = new PNode() {
        private static final long serialVersionUID = -7641452321842902940L;

        /**
         * Return true if this node or any pickable descendends are picked.
         * If a pick occurs the pickPath is modified so that this node is
         * always returned as the picked node, event if it was a decendent
         * node that initialy reported the pick.
         * 
         * @see PComposite
         */
        @Override
        public boolean fullPick(final PPickPath pickPath) {
            if (super.fullPick(pickPath)) {
                PNode picked = pickPath.getPickedNode();
                // this code won't work with internal cameras, because
                // it doesn't pop
                // the cameras view transform.
                while (picked != self) {
                    pickPath.popTransform(picked.getTransformReference(false));
                    pickPath.popNode(picked);
                    picked = pickPath.getPickedNode();
                }
                return true;
            }
            return false;
        }
    };
    { // opaque Background
        final PNode bg = node(new Arc2D.Float(-halo, -halo, 2 * halo, 2 * halo, 0, 360, Arc2D.OPEN), null, null,
                scale0);
        bg.setPaint(bgc);
        bg.setPickable(true);
        handle.addChild(bg);
    }
    { // Cross-hair circles and pie
        final int off = 90;
        final int pieOff = 180;
        final int arrowLengthDegrees = 7;
        // colored pie:
        pie = node(new Arc2D.Float(-outer, -outer, 2 * outer, 2 * outer, off - pieOff, pieAngle, Arc2D.PIE),
                null, null, scale0);
        handle.addChild(pie);
        // inner circle:
        handle.addChild(
                node(new Arc2D.Float(-inner, -inner, 2 * inner, 2 * inner, off, pieOff + pieAngle, Arc2D.OPEN),
                        fine, sp, scale50));
        // outer circle:
        handle.addChild(node(new Arc2D.Float(-outer, -outer, 2 * outer, 2 * outer, off,
                pieOff + pieAngle - (14 + arrowLengthDegrees), Arc2D.OPEN), fine, sp, scale50));
        handle.addChild(
                node(new Arc2D.Float(-outer, -outer, 2 * outer, 2 * outer, off, pieOff + pieAngle, Arc2D.OPEN),
                        fine, sp, -scale50));
        final double ar = Math.PI * (off + pieAngle) / 180.0;
        // radius
        // if (pieAngle % 90 != 0)
        handle.addChild(
                node(new Line2D.Double(0, 0, -outer * Math.cos(ar), outer * Math.sin(ar)), bold, sp, scale0));

        // arrow:
        final float f = outer / 10;
        final PPath s = node(IceShapes.createArrowHead(f, 3 * f, 0.5f * f), null, null, scale50);
        s.setPaint(sp);
        final double a = Math.PI * (off + pieAngle - arrowLengthDegrees) / 180.0;
        s.translate(-outer * Math.cos(a), outer * Math.sin(a));
        s.rotate(Math.PI * (90 - (off + pieAngle) + 8 + arrowLengthDegrees) / 180.0);
        handle.addChild(s);

        this.addChild(handle);
    }
    { // y-axis:
        handle.addChild(
                node(new Line2D.Float(0, -Math.signum(stickLength) * halo, 0, stickLength), fine, sp, scale0));
        // x-axis:
        handle.addChild(node(new Line2D.Float(-halo, 0, halo, 0), fine, sp, scale0));
    }
    { // slider
        slider = new PPath(IceShapes.createSlider(0.4f * outer, bothSides), fine);
        slider.setStrokePaint(sp);
        slider.setPickable(true);
        this.addChild(slider);
    }
    // Set up Event handling
    addInputEventListener(new PDragEventHandler() {

        /** double-click: flip handle */
        @Override
        public void mouseClicked(final PInputEvent arg0) {
            super.mouseClicked(arg0);
            if (arg0.getClickCount() > 1) {
                arg0.setHandled(true);
                first = new HandleMemento(getModel(), getModel().getOutTurn());
                last = new HandleMemento(getModel(), !getModel().getOutTurn());
                ChangeManager.getTrivial(changer).undoable(first, last);
                first = last = null;
            }
        }

        /** drag/move */
        @Override
        public void mouseDragged(final PInputEvent arg0) {
            arg0.setHandled(true);
            getModel().setValueIsAdjusting(true);
            if (false) {
                final Point2D p = arg0.getPositionRelativeTo(self.getParent());
                getModel().setBroom(p);
            } else
                view2model(new XYMemento(getModel(), arg0.getPositionRelativeTo(self.getParent())));
        }

        @Override
        public void mouseEntered(final PInputEvent arg0) {
            super.mouseEntered(arg0);
            arg0.pushCursor(MOVE_CURSOR);
        }

        @Override
        public void mouseExited(final PInputEvent arg0) {
            super.mouseExited(arg0);
            arg0.popCursor();
        }

        @Override
        public void mousePressed(final PInputEvent arg0) {
            arg0.setHandled(true);
            first = new XYMemento(getModel(), getModel().getBroom());
        }

        @Override
        public void mouseReleased(final PInputEvent pinputevent) {
            getModel().setValueIsAdjusting(false);
            if (first != null && last != null && first != last)
                ChangeManager.getTrivial(changer).undoable(first, last);
            first = last = null;
        }
    });
    slider.addInputEventListener(new PDragEventHandler() {
        @Override
        protected void endDrag(final PInputEvent pinputevent) {
            log.debug("speed");
        }

        /** adjust the slider */
        @Override
        public void mouseDragged(final PInputEvent arg0) {
            arg0.setHandled(true);
            final Point2D p = arg0.getPositionRelativeTo(self);
            final BoundedRangeModel r = self.getModel().getSplitTimeMillis();
            if (r == null)
                return;
            r.setValueIsAdjusting(true);
            view2model(new SplitMemento(getModel(), ratio2value(p.getY() / stickLength, r)));
        }

        @Override
        public void mouseEntered(final PInputEvent arg0) {
            super.mouseEntered(arg0);
            arg0.pushCursor(UPDN_CURSOR);
        }

        @Override
        public void mouseExited(final PInputEvent arg0) {
            super.mouseExited(arg0);
            arg0.popCursor();
        }

        @Override
        public void mousePressed(final PInputEvent arg0) {
            arg0.setHandled(true);
            first = new SplitMemento(getModel(), getModel().getSplitTimeMillis().getValue());
        }

        @Override
        public void mouseReleased(final PInputEvent pinputevent) {
            log.debug("speed");
            final BoundedRangeModel r = self.getModel().getSplitTimeMillis();
            if (r == null)
                return;
            r.setValueIsAdjusting(false);
            if (first != null && last != null && first != last)
                ChangeManager.getTrivial(changer).undoable(first, last);
            first = last = null;
        }
    });
}

From source file:org.kalypso.kalypsomodel1d2d.ui.map.RefineFEGeometryWidget.java

private void drawRefinement(final Graphics g, final GeoTransform projection)
        throws CoreException, GM_Exception {
    /* Paint a rect. */
    final LineSymbolizer symb = new LineSymbolizer_Impl();
    final Stroke stroke = new Stroke_Impl(new HashMap<String, CssParameter>(), null, null);
    final Color color = new Color(255, 0, 0);
    for (final GM_Object object : m_objects) {
        if (object instanceof GM_Polygon) {
            final GM_Polygon surface = (GM_Polygon) object;
            final String crs = surface.getCoordinateSystem();

            for (final GM_AbstractSurfacePatch surfacePatch : surface) {
                final GM_Position[] exteriorRing = surfacePatch.getExteriorRing();
                final GM_Curve curve = org.kalypsodeegree_impl.model.geometry.GeometryFactory
                        .createGM_Curve(exteriorRing, crs);

                stroke.setWidth(3);//from  w  w w . j  a v  a 2s .  c o  m
                stroke.setLineCap(BasicStroke.CAP_ROUND);
                stroke.setLineJoin(BasicStroke.JOIN_ROUND);
                stroke.setStroke(color);
                symb.setStroke(stroke);

                final DisplayElement de = DisplayElementFactory.buildLineStringDisplayElement(null, curve,
                        symb);
                de.paint(g, projection, new NullProgressMonitor());
            }
        }
    }
}

From source file:org.pentaho.chart.plugin.jfreechart.utils.StrokeFactory.java

/**
* This method creates a BasicStroke object for border-style/line-style like dotted, solid etc
* It also incorporates border-width for the border/line width for the line.
* <p/>//from  www .j a  va  2  s.com
* NONE, HIDDEN, SOLID, DASHED, DOT-DASH and DOTTED are the only border-style/line-style
* that we currently support.
* The border-width/line-width: thin, medium and thick have been mapped to static widths.
*
* @param chartElement The current series element
* @param widthStyleKey The Width style key. 
* @param styleStyleKey The Style style key.
* @return BasicStroke  The basic stroke object that implements the style and width.
*/
private BasicStroke getBasicStroke(final ChartElement chartElement, final StyleKey styleStyleKey,
        final StyleKey widthStyleKey) {
    CSSValue cssValue = chartElement.getLayoutStyle().getValue(widthStyleKey);
    final String borderWidth = (cssValue != null ? cssValue.getCSSText() : null);

    float width = 0f;
    if (borderWidth != null) {
        if (borderWidth.equalsIgnoreCase(BorderWidth.THIN.toString())) {
            width = THIN;
        } else if (borderWidth.equalsIgnoreCase(BorderWidth.MEDIUM.toString())) {
            width = MEDIUM;
        } else if (borderWidth.equalsIgnoreCase(BorderWidth.THICK.toString())) {
            width = THICK;
        } else if (borderWidth.endsWith(PIXEL)) {
            final String borderWidthPixels = (borderWidth.substring(0, borderWidth.indexOf(PIXEL))).trim();
            width = Integer.parseInt(borderWidthPixels);
        } else if (borderWidth.endsWith(CENTIMETER)) {
            final String borderWidthCms = (borderWidth.substring(0, borderWidth.indexOf(CENTIMETER))).trim();
            // Convert centimeter to pixels
            width = Integer.parseInt(borderWidthCms) * CENTIMETER_TO_PIXEL;
        }
    }

    final CSSValue borderStyle = chartElement.getLayoutStyle().getValue(styleStyleKey);
    if ((borderStyle == null) || BorderStyle.NONE.getCSSText().equals(borderStyle.getCSSText())) {
        // TODO mlowery figure out why logging won't output a "lesser" priority for this call
        logger.warn(String.format("************style %s has value %s; stroke will be null", styleStyleKey.name,
                BorderStyle.NONE.getCSSText()));
        return null;
    }

    BasicStroke stroke = null;

    if (BorderStyle.SOLID.equals(borderStyle)) {
        stroke = new BasicStroke(width);
    } else if (BorderStyle.DASHED.equals(borderStyle)) {
        stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0F,
                new float[] { 10.0F, 3.0F }, 0.F);
    } else if (BorderStyle.DOT_DASH.equals(borderStyle)) {
        stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0F,
                new float[] { 10.0F, 3.0F, 2.0F, 2.0F }, 0.F);
    } else if (BorderStyle.DOTTED.equals(borderStyle)) {
        stroke = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0,
                new float[] { 0, 6, 0, 6 }, 0);
    }
    return stroke;
}

From source file:savant.view.swing.GraphPane.java

@Override
protected void paintComponent(Graphics g) {
    if (tracks != null && tracks.length > 0) {
        LOG.trace("GraphPane.paintComponent(" + tracks[0].getName() + ")");
    }//from  w  w w  .jav a2s  . co m
    super.paintComponent(g);

    Graphics2D g2 = (Graphics2D) g;
    boolean trueRender = render(g2);

    GraphPaneController gpc = GraphPaneController.getInstance();
    int h = getHeight();

    // Aiming adjustments.
    if (gpc.isAiming() && mouseInside) {
        g2.setColor(Color.BLACK);
        Font thickfont = g2.getFont().deriveFont(Font.BOLD, 15.0F);
        g2.setFont(thickfont);
        int genomeX = gpc.getMouseXPosition();
        double genomeY = gpc.getMouseYPosition();
        String target = "";
        target += "X: " + MiscUtils.numToString(genomeX);
        if (!Double.isNaN(genomeY)) {
            target += " Y: " + MiscUtils.numToString(genomeY);
        }

        g2.drawLine(mouseX, 0, mouseX, h);
        if (genomeY != -1) {
            g.drawLine(0, mouseY, this.getWidth(), mouseY);
        }
        g2.drawString(target, mouseX + 5, mouseY - 5);
    }

    double x1 = transformXPos(gpc.getMouseClickPosition());
    double x2 = transformXPos(gpc.getMouseReleasePosition());

    double width = x1 - x2;

    selectionRect = new Rectangle2D.Double(width < 0 ? x1 : x2, 0.0, Math.max(2.0, Math.abs(width)), h);

    if (gpc.isPanning()) {
        // Panning adjustments (none).
    } else if (gpc.isZooming() || gpc.isSelecting()) {
        // Zooming adjustments.
        Rectangle2D rectangle = new Rectangle2D.Double(selectionRect.getX(), selectionRect.getY() - 10.0,
                selectionRect.getWidth(), selectionRect.getHeight() + 10.0);
        g2.setColor(Color.gray);
        g2.setStroke(
                new BasicStroke(1f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 3f, new float[] { 4f }, 4f));
        g2.draw(rectangle);

        if (gpc.isZooming()) {
            g.setColor(ColourSettings.getColor(ColourKey.GRAPH_PANE_ZOOM_FILL));
        } else if (gpc.isSelecting()) {
            g.setColor(ColourSettings.getColor(ColourKey.GRAPH_PANE_SELECTION_FILL));
        }
        g2.fill(selectionRect);
    }

    // Plumbing adjustments.
    Range xRange = getXRange();
    if (gpc.isPlumbing()) {
        g2.setColor(Color.BLACK);
        double spos = transformXPos(gpc.getMouseXPosition());
        g2.draw(new Line2D.Double(spos, 0, spos, h));
        double rpos = transformXPos(gpc.getMouseXPosition() + 1);
        g2.draw(new Line2D.Double(rpos, 0, rpos, h));
    }

    // Spotlight
    if (gpc.isSpotlight() && !gpc.isZooming()) {

        int center = gpc.getMouseXPosition();
        int left = center - gpc.getSpotlightSize() / 2;
        int right = left + gpc.getSpotlightSize();

        g2.setColor(new Color(0, 0, 0, 200));

        // draw left of spotlight
        if (left >= xRange.getFrom()) {
            g2.fill(new Rectangle2D.Double(0.0, 0.0, transformXPos(left), h));
        }
        // draw right of spotlight
        if (right <= xRange.getTo()) {
            double pix = transformXPos(right);
            g2.fill(new Rectangle2D.Double(pix, 0, getWidth() - pix, h));
        }
    }

    if (isLocked()) {
        drawMessage((Graphics2D) g, "Locked");
    }
    if (trueRender) {
        gpc.delistRenderingGraphpane(this);
    }
}

From source file:se.ngm.ditaaeps.EpsRenderer.java

public static void renderToEps(Diagram diagram, PrintWriter out, RenderingOptions options) {
    //RenderedImage renderedImage = image;
    EpsGraphics2D g2 = new EpsGraphics2D(out,
            new Rectangle2D.Double(0, -diagram.getHeight(), diagram.getWidth(), diagram.getHeight()));

    g2.scale(1, -1); // g2 origo is top-left, eps is bottom-left

    Object antialiasSetting = antialiasSetting = RenderingHints.VALUE_ANTIALIAS_OFF;
    if (options.performAntialias())
        antialiasSetting = RenderingHints.VALUE_ANTIALIAS_ON;

    //g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialiasSetting);

    g2.setColor(Color.white);//from   ww  w  .  java2 s . co  m
    //TODO: find out why the next line does not work
    //g2.fillRect(0, 0, image.getWidth()+10, image.getHeight()+10);
    /*for(int y = 0; y < diagram.getHeight(); y ++)
      g2.drawLine(0, y, diagram.getWidth(), y);*/

    g2.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND));

    ArrayList shapes = diagram.getAllDiagramShapes();

    if (DEBUG)
        System.out.println("Rendering " + shapes.size() + " shapes (groups flattened)");

    Iterator shapesIt;
    if (options.dropShadows()) {
        //render shadows
        shapesIt = shapes.iterator();
        while (shapesIt.hasNext()) {
            DiagramShape shape = (DiagramShape) shapesIt.next();

            if (shape.getPoints().isEmpty())
                continue;

            //GeneralPath path = shape.makeIntoPath();
            GeneralPath path;
            path = shape.makeIntoRenderPath(diagram);

            float offset = diagram.getMinimumOfCellDimension() / 3.333f;

            if (path != null && shape.dropsShadow()) {
                GeneralPath shadow = new GeneralPath(path);
                AffineTransform translate = new AffineTransform();
                translate.setToTranslation(offset, offset);
                shadow.transform(translate);
                g2.setColor(new Color(150, 150, 150));
                g2.fill(shadow);

            }
        }

        //blur shadows

        //            if(true) {
        //                int blurRadius = 6;
        //                int blurRadius2 = blurRadius * blurRadius;
        //                float blurRadius2F = blurRadius2;
        //                float weight = 1.0f / blurRadius2F;
        //                float[] elements = new float[blurRadius2];
        //                for (int k = 0; k < blurRadius2; k++)
        //                    elements[k] = weight;
        //                Kernel myKernel = new Kernel(blurRadius, blurRadius, elements);
        //
        //                //if EDGE_NO_OP is not selected, EDGE_ZERO_FILL is the default which creates a black border
        //                ConvolveOp simpleBlur =
        //                        new ConvolveOp(myKernel, ConvolveOp.EDGE_NO_OP, null);
        //                //BufferedImage destination = new BufferedImage(image.getWidth()+blurRadius, image.getHeight()+blurRadius, image.getType());
        //                BufferedImage destination =
        //                        new BufferedImage(
        //                        image.getWidth(),
        //                        image.getHeight(),
        //                        image.getType());
        //                simpleBlur.filter(image, destination);
        //                //destination = destination.getSubimage(blurRadius/2, blurRadius/2, image.getWidth(), image.getHeight());
        //                g2 = destination.createGraphics();
        //                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialiasSetting);
        //                renderedImage = destination;
        //            }
    }

    //fill and stroke

    float dashInterval = Math.min(diagram.getCellWidth(), diagram.getCellHeight()) / 2;
    //Stroke normalStroke = g2.getStroke();

    float strokeWeight = diagram.getMinimumOfCellDimension() / 10;

    Stroke normalStroke = new BasicStroke(strokeWeight,
            //10,
            BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);

    Stroke dashStroke = new BasicStroke(strokeWeight, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 0,
            new float[] { dashInterval }, 0);

    //find storage shapes
    ArrayList storageShapes = new ArrayList();
    shapesIt = shapes.iterator();
    while (shapesIt.hasNext()) {
        DiagramShape shape = (DiagramShape) shapesIt.next();
        if (shape.getType() == DiagramShape.TYPE_STORAGE) {
            storageShapes.add(shape);
            continue;
        }
    }

    //render storage shapes
    //special case since they are '3d' and should be
    //rendered bottom to top
    //TODO: known bug: if a storage object is within a bigger normal box, it will be overwritten in the main drawing loop
    //(BUT this is not possible since tags are applied to all shapes overlaping shapes)

    Collections.sort(storageShapes, new Shape3DOrderingComparator());

    g2.setStroke(normalStroke);
    shapesIt = storageShapes.iterator();
    while (shapesIt.hasNext()) {
        DiagramShape shape = (DiagramShape) shapesIt.next();

        GeneralPath path;
        path = shape.makeIntoRenderPath(diagram);

        if (!shape.isStrokeDashed()) {
            if (shape.getFillColor() != null)
                g2.setColor(shape.getFillColor());
            else
                g2.setColor(Color.white);
            g2.fill(path);
        }

        if (shape.isStrokeDashed())
            g2.setStroke(dashStroke);
        else
            g2.setStroke(normalStroke);
        g2.setColor(shape.getStrokeColor());
        g2.draw(path);
    }

    //render the rest of the shapes
    ArrayList pointMarkers = new ArrayList();
    shapesIt = shapes.iterator();
    while (shapesIt.hasNext()) {
        DiagramShape shape = (DiagramShape) shapesIt.next();
        if (shape.getType() == DiagramShape.TYPE_POINT_MARKER) {
            pointMarkers.add(shape);
            continue;
        }
        if (shape.getType() == DiagramShape.TYPE_STORAGE) {
            continue;
        }

        if (shape.getPoints().isEmpty())
            continue;

        int size = shape.getPoints().size();

        GeneralPath path;
        path = shape.makeIntoRenderPath(diagram);

        if (path != null && shape.isClosed() && !shape.isStrokeDashed()) {
            if (shape.getFillColor() != null)
                g2.setColor(shape.getFillColor());
            else
                g2.setColor(Color.white);
            g2.fill(path);
        }
        if (shape.getType() != DiagramShape.TYPE_ARROWHEAD) {
            g2.setColor(shape.getStrokeColor());
            if (shape.isStrokeDashed())
                g2.setStroke(dashStroke);
            else
                g2.setStroke(normalStroke);
            g2.draw(path);
        }
    }

    //render point markers

    g2.setStroke(normalStroke);
    shapesIt = pointMarkers.iterator();
    while (shapesIt.hasNext()) {
        DiagramShape shape = (DiagramShape) shapesIt.next();
        //if(shape.getType() != DiagramShape.TYPE_POINT_MARKER) continue;

        GeneralPath path;
        path = shape.makeIntoRenderPath(diagram);

        g2.setColor(Color.white);
        g2.fill(path);
        g2.setColor(shape.getStrokeColor());
        g2.draw(path);
    }

    //handle text
    //g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);

    Iterator textIt = diagram.getTextObjects().iterator();
    while (textIt.hasNext()) {
        DiagramText text = (DiagramText) textIt.next();
        g2.setColor(text.getColor());
        g2.setFont(text.getFont());
        g2.drawString(text.getText(), text.getXPos(), text.getYPos());
    }

    if (options.renderDebugLines() || DEBUG) {
        Stroke debugStroke = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        g2.setStroke(debugStroke);
        g2.setColor(new Color(170, 170, 170));
        g2.setXORMode(Color.white);
        for (int x = 0; x < diagram.getWidth(); x += diagram.getCellWidth())
            g2.drawLine(x, 0, x, diagram.getHeight());
        for (int y = 0; y < diagram.getHeight(); y += diagram.getCellHeight())
            g2.drawLine(0, y, diagram.getWidth(), y);
    }

    g2.dispose();
}

From source file:uk.ac.liverpool.narrative.SolutionGraphics.java

public void createVisualStateGraph(boolean dynamic, int iterations) {

    KKLayout<STRIPSState, Action> layout = new KKLayout<STRIPSState, Action>(sg.ggraph);// , new SDist<STRIPSState, Action>(ggraph));

    layout.setLengthFactor(1.7);//from  ww w  .  j a va  2s . c  om
    layout.setAdjustForGravity(false);
    // layout.setDisconnectedDistanceMultiplier(1.5);
    // layout.setExchangeVertices(true);
    layout.setSize(new Dimension(2000, 1200)); // sets the initial size of
    int i = 0;
    if (!dynamic) {
        layout.setMaxIterations(iterations);
        while (!layout.done() && i++ < iterations) {
            layout.step();
        }
        layout.lock(true);
    }
    final VisualizationViewer<STRIPSState, Action> vv = new VisualizationViewer<STRIPSState, Action>(layout);
    vvv = vv;
    vv.setPreferredSize(new Dimension(2000, 1200)); // Sets the viewing area

    final DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse();
    graphMouse.setMode(ModalGraphMouse.Mode.PICKING);
    vv.setGraphMouse(graphMouse);

    vv.setBackground(Color.white);
    vv.getRenderContext().setVertexLabelTransformer(new ConstantTransformer(""));
    vv.getRenderContext().setEdgeFontTransformer(new Transformer<Action, Font>() {
        @Override
        public Font transform(Action s) {

            Action ra = sg.realActions.get(s);
            Collection<Action> set = sg.actionToEdges.get(template.apply_template(ra));
            if (set != null && set.size() > 1)
                return DERIVE_FONT;
            return DERIVE_FONT2;
        }
    });

    vv.getRenderContext().setEdgeLabelTransformer(new Transformer<Action, String>() {
        @Override
        public String transform(Action a) {
            try {
                return sg.actionToString(template, a);
            } catch (IOException e) {
                e.printStackTrace();
                return "";
            }
        }
    });

    vv.getRenderContext().setEdgeDrawPaintTransformer(new Transformer<Action, Paint>() {
        @Override
        public Paint transform(Action s) {
            sg.realActions.get(s);
            EdgeColor v = sg.edgeColors.get(s);
            if (v == null)
                return Color.yellow;
            if (v == EdgeColor.black)
                return Color.red;
            else
                return Color.lightGray;
        }
    });
    vv.getRenderContext().setVertexStrokeTransformer(new ConstantTransformer(new BasicStroke(0)));
    vv.getRenderContext().setVertexFillPaintTransformer(new Transformer<STRIPSState, Paint>() {

        @Override
        public Paint transform(STRIPSState s) {
            if (vv.getPickedVertexState().isPicked(s))
                return new Color(250, 250, 0, 207);
            Color c = cm.get(s);
            if (c != null)
                return c;

            if (sg.start.equals(s))
                return new Color(10, 200, 10, 197);
            else if (sg.ends.contains(s))
                return new Color(220, 10, 10, 197);
            return new Color(255, 210, 40, 197);
        }
    });
    vv.getRenderContext().setVertexShapeTransformer(new StoryStateTransformer());
    vv.getRenderContext()
            .setEdgeArrowTransformer(new DirectionalEdgeArrowTransformer<STRIPSState, Action>(10, 8, 1) {
                @Override
                public Shape transform(Context<Graph<STRIPSState, Action>, Action> context) {
                    if (sg.frequency.get(sg.ggraph.getEndpoints(context.element).getFirst()) != null) {
                        double c = Math.log(
                                sg.frequency.get(sg.ggraph.getEndpoints(context.element).getFirst())) * 0.8;
                        if (c > 1) {
                            Shape ss = AffineTransform.getScaleInstance(c, c)
                                    .createTransformedShape(super.transform(context));
                            return ss;
                        }
                    }

                    return super.transform(context);
                }

            });

    vv.setRenderer(new LabelsLastRenderer());

    vv.getRenderer().getVertexLabelRenderer().setPosition(Position.AUTO);
    vv.getRenderContext().setEdgeStrokeTransformer(new Transformer<Action, Stroke>() {

        @Override
        public Stroke transform(Action a) {
            if (false)
                return new BasicStroke(
                        (sg.actionToEdges.get(template.apply_template(sg.realActions.get(a))).size()),
                        BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
            if (sg.frequency.get(sg.ggraph.getEndpoints(a).getFirst()) != null)
                return new BasicStroke(
                        (float) (Math.log(sg.frequency.get(sg.ggraph.getEndpoints(a).getFirst())) * 6.0),
                        BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
            else
                return new BasicStroke(1);
        }
    });
    vv.getRenderContext().setEdgeLabelRenderer(new DefaultEdgeLabelRenderer(Color.gray, false));
    vv.getRenderContext().setLabelOffset(20);
    vv.getRenderContext().setArrowFillPaintTransformer(new ConstantTransformer(Color.lightGray));

    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);

    JPanel jp = new JPanel();
    jp.setBackground(Color.WHITE);
    jp.setLayout(new BorderLayout());
    jp.add(panel, BorderLayout.CENTER);
    JPanel top = new JPanel(new FlowLayout());

    jp.add(top, BorderLayout.NORTH);
    JFrame frame = new JFrame("Story state graph");
    frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    frame.getContentPane().add(jp);
    frame.pack();
    frame.setVisible(true);

}