Example usage for java.awt.geom Point2D getX

List of usage examples for java.awt.geom Point2D getX

Introduction

In this page you can find the example usage for java.awt.geom Point2D getX.

Prototype

public abstract double getX();

Source Link

Document

Returns the X coordinate of this Point2D in double precision.

Usage

From source file:com.net2plan.gui.utils.topologyPane.jung.JUNGCanvas.java

@Override
public void moveCanvasTo(Point2D destinationPoint) {
    final MutableTransformer layoutTransformer = vv.getRenderContext().getMultiLayerTransformer()
            .getTransformer(Layer.LAYOUT);
    layoutTransformer.translate(destinationPoint.getX(), destinationPoint.getY());
}

From source file:gov.llnl.lc.infiniband.opensm.plugin.gui.graph.CollapsableGraphView.java

public CollapsableGraphView(Graph graph, boolean val) throws HeadlessException {
    super();/*from   w w w.  j a  v a 2 s .com*/
    setGraph(graph);

    layout = new FRLayout(graph);
    Dimension preferredSize = new Dimension(400, 400);
    final VisualizationModel visualizationModel = new DefaultVisualizationModel(layout, preferredSize);
    VisualizationViewer vv = new VisualizationViewer(visualizationModel, preferredSize);

    vv.addGraphMouseListener(new CollapsableGraphMouseListener<Number>());

    vv.getRenderContext().setVertexShapeTransformer(new ClusterVertexShapeTransformer());

    PickedState<Integer> picked_state = vv.getPickedVertexState();

    // create decorators
    vv.getRenderContext().setVertexFillPaintTransformer(IB_TransformerFactory.getDefaultPaintTransformer(vv));

    setVisViewer(vv);

    final PredicatedParallelEdgeIndexFunction eif = PredicatedParallelEdgeIndexFunction.getInstance();
    final Set exclusions = new HashSet();
    eif.setPredicate(new Predicate() {

        public boolean evaluate(Object e) {

            return exclusions.contains(e);
        }
    });

    vv.getRenderContext().setParallelEdgeIndexFunction(eif);

    vv.setBackground(Color.white);

    // add a listener for ToolTips

    vv.setVertexToolTipTransformer(new ToStringLabeller() {

        /*
         * (non-Javadoc)
         * 
         * @see edu.uci.ics.jung.visualization.decorators.DefaultToolTipFunction#
         * getToolTipText(java.lang.Object)
         */
        @Override
        public String transform(Object v) {
            if (v instanceof Graph) {
                return ((Graph) v).getVertices().toString();
            }
            return super.transform(v);
        }
    });

    /**
     * the regular graph mouse for the normal view
     */
    final DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse();

    vv.setGraphMouse(graphMouse);

    Container content = getContentPane();
    GraphZoomScrollPane gzsp = new GraphZoomScrollPane(vv);
    content.add(gzsp);

    JComboBox modeBox = graphMouse.getModeComboBox();
    modeBox.addItemListener(graphMouse.getModeListener());
    graphMouse.setMode(ModalGraphMouse.Mode.PICKING);

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            VisualizationViewer vv = getVisViewer();
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            VisualizationViewer vv = getVisViewer();
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JButton collapse = new JButton("Collapse");
    collapse.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            System.out.println("Collapsing the graph");

            // Pick all port zeros, and their IMMEDIATE links
            //        PickManager.getInstance().pickAllSwitches(vv);

            VisualizationViewer vv = getVisViewer();
            Collection picked = new HashSet(vv.getPickedVertexState().getPicked());
            if (picked.size() > 1) {
                System.out.println("CGV: The number picked is: " + picked.size());
                Graph inGraph = layout.getGraph();
                Graph clusterGraph = collapser.getClusterGraph(inGraph, picked);

                Graph g = collapser.collapse(layout.getGraph(), clusterGraph);
                collapsedGraph = g;
                double sumx = 0;
                double sumy = 0;
                for (Object v : picked) {
                    Point2D p = (Point2D) layout.transform(v);
                    sumx += p.getX();
                    sumy += p.getY();
                }
                Point2D cp = new Point2D.Double(sumx / picked.size(), sumy / picked.size());
                vv.getRenderContext().getParallelEdgeIndexFunction().reset();
                layout.setGraph(g);
                layout.setLocation(clusterGraph, cp);
                vv.getPickedVertexState().clear();
                vv.repaint();
            }

            // Collection picked = new
            // HashSet(vv.getPickedVertexState().getPicked());
            // if (picked.size() > 1)
            // {
            // Graph inGraph = layout.getGraph();
            // Graph clusterGraph = collapser.getClusterGraph(inGraph, picked);
            //
            // Graph g = collapser.collapse(layout.getGraph(), clusterGraph);
            // collapsedGraph = g;
            // double sumx = 0;
            // double sumy = 0;
            // for (Object v : picked)
            // {
            // Point2D p = (Point2D) layout.transform(v);
            // sumx += p.getX();
            // sumy += p.getY();
            // }
            // Point2D cp = new Point2D.Double(sumx / picked.size(), sumy /
            // picked.size());
            // vv.getRenderContext().getParallelEdgeIndexFunction().reset();
            // layout.setGraph(g);
            // layout.setLocation(clusterGraph, cp);
            // vv.getPickedVertexState().clear();
            // vv.repaint();
            // }

        }

    });

    JButton compressEdges = new JButton("Compress Edges");
    compressEdges.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            VisualizationViewer vv = getVisViewer();
            Collection picked = vv.getPickedVertexState().getPicked();
            if (picked.size() == 2) {
                Pair pair = new Pair(picked);
                Graph graph = layout.getGraph();
                Collection edges = new HashSet(graph.getIncidentEdges(pair.getFirst()));
                edges.retainAll(graph.getIncidentEdges(pair.getSecond()));
                getExclusions().addAll(edges);
                vv.repaint();
            }

        }
    });

    JButton expandEdges = new JButton("Expand Edges");
    expandEdges.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            VisualizationViewer vv = getVisViewer();
            Collection picked = vv.getPickedVertexState().getPicked();
            if (picked.size() == 2) {
                Pair pair = new Pair(picked);
                Graph graph = layout.getGraph();
                Collection edges = new HashSet(graph.getIncidentEdges(pair.getFirst()));
                edges.retainAll(graph.getIncidentEdges(pair.getSecond()));
                getExclusions().removeAll(edges);
                vv.repaint();
            }

        }
    });

    JButton expand = new JButton("Expand");
    expand.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            VisualizationViewer vv = getVisViewer();
            Collection picked = new HashSet(vv.getPickedVertexState().getPicked());
            for (Object v : picked) {
                if (v instanceof Graph) {

                    Graph g = collapser.expand(layout.getGraph(), (Graph) v);
                    vv.getRenderContext().getParallelEdgeIndexFunction().reset();
                    layout.setGraph(g);
                }
                vv.getPickedVertexState().clear();
                vv.repaint();
            }
        }
    });

    JButton reset = new JButton("Reset");
    reset.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            VisualizationViewer vv = getVisViewer();
            Graph g = getGraph();
            layout.setGraph(g);
            getExclusions().clear();
            vv.repaint();
        }
    });

    JButton help = new JButton("Help");
    help.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog((JComponent) e.getSource(), getInstructions(), "Help",
                    JOptionPane.PLAIN_MESSAGE);
        }
    });
    Class[] combos = getCombos();
    final JComboBox jcb = new JComboBox(combos);
    // use a renderer to shorten the layout name presentation
    jcb.setRenderer(new DefaultListCellRenderer() {
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            String valueString = value.toString();
            valueString = valueString.substring(valueString.lastIndexOf('.') + 1);
            return super.getListCellRendererComponent(list, valueString, index, isSelected, cellHasFocus);
        }
    });
    jcb.addActionListener(new LayoutChooser(jcb, vv, this));
    jcb.setSelectedItem(FRLayout.class);

    JPanel controls = new JPanel();
    JPanel zoomControls = new JPanel(new GridLayout(2, 1));
    zoomControls.setBorder(BorderFactory.createTitledBorder("Zoom"));
    zoomControls.add(plus);
    zoomControls.add(minus);
    controls.add(zoomControls);
    JPanel collapseControls = new JPanel(new GridLayout(3, 1));
    collapseControls.setBorder(BorderFactory.createTitledBorder("Picked"));
    collapseControls.add(collapse);
    collapseControls.add(expand);
    collapseControls.add(compressEdges);
    collapseControls.add(expandEdges);
    collapseControls.add(reset);
    controls.add(collapseControls);
    controls.add(modeBox);
    controls.add(help);
    controls.add(jcb);
    content.add(controls, BorderLayout.SOUTH);
}

From source file:Hexagon.java

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("[Hexagon: ");
    sb.append(String.format("[Size: %d]", size));
    sb.append(String.format("[Height: %2.1f, hOffset: %2.1f]", height, hOffset));
    sb.append(String.format("[Width: %2.1f, wOffset: %2.1f]", width, wOffset));
    sb.append(String.format("[Center: %2.1fx%2.1f]", center.getX(), center.getY()));

    sb.append("[Corners: ");
    for (Corner corner : Corner.values()) {
        Point2D p2d = corners.get(corner);
        sb.append(String.format("[%s: %2.1fx%2.1f]", corner, p2d.getX(), p2d.getY()));
    }/*from w w  w  . j a  va  2 s.  c  o m*/
    sb.append("]");

    sb.append("[Bounds: ");
    for (BoundingCorner corner : BoundingCorner.values()) {
        Point2D p2d = boundingCorners.get(corner);
        sb.append(String.format("[%s: %2.1fx%2.1f]", corner, p2d.getX(), p2d.getY()));
    }
    sb.append("]");

    sb.append(String.format("[BoundingBox: %2.1fx%2.1f to %2.1fx%2.1f]", boundingBox.getMinX(),
            boundingBox.getMinY(), boundingBox.getMaxX(), boundingBox.getMaxY()));

    sb.append("]");
    return sb.toString();
}

From source file:org.geoserver.wms.map.QuickTileCache.java

/**
 * Given an envelope and origin, find the tile coordinate (row,col)
 * //  ww w.j a v  a 2 s. c  o m
 * @param env
 * @param origin
 * @return
 */
Point getTileCoordinates(Envelope env, Point2D origin) {
    // this was using the low left corner and Math.round, but turned
    // out to be fragile when fairly zoomed in. Using the tile center
    // and then flooring the division seems to work much more reliably.
    double centerx = env.getMinX() + env.getWidth() / 2;
    double centery = env.getMinY() + env.getHeight() / 2;
    int x = (int) Math.floor((centerx - origin.getX()) / env.getWidth());
    int y = (int) Math.floor((centery - origin.getY()) / env.getWidth());

    return new Point(x, y);
}

From source file:org.geoserver.wms.map.QuickTileCache.java

/**
 * Given a tiled request, builds a key that can be used to access the cache looking for a
 * specific meta-tile, and also as a synchronization tool to avoid multiple requests to trigger
 * parallel computation of the same meta-tile
 * //from w w w  .jav a 2 s  .com
 * @param request
 * @return
 */
public MetaTileKey getMetaTileKey(GetMapRequest request) {
    String mapDefinition = buildMapDefinition(request.getRawKvp());
    ReferencedEnvelope bbox = new ReferencedEnvelope(request.getBbox(), request.getCrs());
    Point2D origin = request.getTilesOrigin();
    if (CRS.getAxisOrder(request.getCrs()) == AxisOrder.NORTH_EAST) {
        try {
            bbox = new ReferencedEnvelope(bbox.getMinY(), bbox.getMaxY(), bbox.getMinX(), bbox.getMaxX(),
                    CRS.decode("EPSG:" + CRS.lookupEpsgCode(request.getCrs(), false)));
            origin = new Point2D.Double(origin.getY(), origin.getX());
        } catch (Exception e) {
            throw new ServiceException("Failed to bring the bbox back in a EN order", e);
        }
    }
    MapKey mapKey = new MapKey(mapDefinition, normalize(bbox.getWidth() / request.getWidth()), origin);
    Point tileCoords = getTileCoordinates(bbox, origin);
    Point metaTileCoords = getMetaTileCoordinates(tileCoords);
    ReferencedEnvelope metaTileEnvelope = getMetaTileEnvelope(bbox, tileCoords, metaTileCoords);
    MetaTileKey key = new MetaTileKey(mapKey, metaTileCoords, metaTileEnvelope);

    // since this will be used for thread synchronization, we have to make
    // sure two thread asking for the same meta tile will get the same key
    // object
    return (MetaTileKey) metaTileKeys.unique(key);
}

From source file:com.net2plan.gui.utils.topologyPane.jung.JUNGCanvas.java

/**
 * Default constructor.//from w  w  w. jav  a2 s . c  o m
 *
 * @since 0.2.3
 */
public JUNGCanvas(IVisualizationCallback callback, TopologyPanel topologyPanel) {
    this.callback = callback;

    transformNetPlanCoordinatesToJungCoordinates = vertex -> {
        final int vlIndex = this.callback.getVisualizationState()
                .getCanvasVisualizationOrderRemovingNonVisible(vertex.getLayer());
        final double interLayerDistanceInNpCoord = currentInterLayerDistanceInNpCoordinates;
        final Point2D basePositionInNetPlanCoord = vertex.getAssociatedNetPlanNode().getXYPositionMap();
        return new Point2D.Double(basePositionInNetPlanCoord.getX(),
                -(basePositionInNetPlanCoord.getY() + (vlIndex * interLayerDistanceInNpCoord)));
    };

    g = new DirectedOrderedSparseMultigraph<>();
    l = new StaticLayout<>(g, transformNetPlanCoordinatesToJungCoordinates);
    vv = new VisualizationViewer<>(l);

    osmStateManager = new OSMStateManager(callback, topologyPanel, this);

    originalEdgeShapeTransformer = new EdgeShape.QuadCurve<>();
    ((EdgeShape.QuadCurve<GUINode, GUILink>) originalEdgeShapeTransformer).setControlOffsetIncrement(10); // how much they separate from the direct line (default is 20)
    //((EdgeShape.QuadCurve<GUINode, GUILink>) originalEdgeShapeTransformer).setEdgeIndexFunction(DefaultParallelEdgeIndexFunction.<GUINode, GUILink>getInstance()); // how much they separate from the direct line (default is 20)
    /* This functions gives an index to the links to show separate (curved): the order among the parallel links (BUT NOW only among the separated ones among them) */
    ((EdgeShape.QuadCurve<GUINode, GUILink>) originalEdgeShapeTransformer)
            .setEdgeIndexFunction(new EdgeIndexFunction<GUINode, GUILink>() {
                public void reset(Graph<GUINode, GUILink> graph, GUILink e) {
                }

                public void reset() {
                }

                public int getIndex(Graph<GUINode, GUILink> graph, GUILink e) {
                    final GUINode u = e.getOriginNode();
                    final GUINode v = e.getDestinationNode();
                    final HashSet<GUILink> commonEdgeSet = new HashSet<>(graph.getInEdges(v));
                    commonEdgeSet.retainAll(graph.getOutEdges(u));
                    commonEdgeSet.removeIf(ee -> !ee.isShownSeparated());
                    int count = 0;
                    for (GUILink other : commonEdgeSet)
                        if (other == e)
                            return count;
                        else
                            count++;
                    throw new RuntimeException();
                }
            });
    /* Customize the graph */
    vv.getRenderContext().setVertexDrawPaintTransformer(n -> n.getDrawPaint());
    vv.getRenderContext().setVertexFillPaintTransformer(n -> n.getFillPaint());
    vv.getRenderContext().setVertexFontTransformer(n -> n.getFont());

    vv.getRenderContext().setVertexIconTransformer(gn -> gn.getIcon());

    vv.getRenderContext().setVertexIncludePredicate(
            guiNodeContext -> callback.getVisualizationState().isVisibleInCanvas(guiNodeContext.element));
    vv.getRenderer().setVertexLabelRenderer(new NodeLabelRenderer());
    vv.setVertexToolTipTransformer(node -> node.getToolTip());

    vv.getRenderContext().setEdgeIncludePredicate(
            context -> callback.getVisualizationState().isVisibleInCanvas(context.element));
    vv.getRenderContext().setEdgeArrowPredicate(
            context -> callback.getVisualizationState().isVisibleInCanvas(context.element)
                    && context.element.getHasArrow());
    vv.getRenderContext().setEdgeArrowStrokeTransformer(i -> i.getArrowStroke());
    vv.getRenderContext()
            .setEdgeArrowTransformer(new ConstantTransformer(ArrowFactory.getNotchedArrow(7, 10, 5)));
    vv.getRenderContext().setEdgeLabelClosenessTransformer(new ConstantDirectionalEdgeValueTransformer(.6, .6));
    vv.getRenderContext().setEdgeStrokeTransformer(i -> i.getEdgeStroke());

    vv.getRenderContext().setEdgeDrawPaintTransformer(e -> e.getEdgeDrawPaint());
    vv.getRenderContext().setArrowDrawPaintTransformer(e -> e.getArrowDrawPaint());
    vv.getRenderContext().setArrowFillPaintTransformer(e -> e.getArrowFillPaint());

    vv.getRenderContext().setEdgeLabelRenderer(new DefaultEdgeLabelRenderer(Color.BLUE));
    vv.getRenderer().setEdgeLabelRenderer(new BasicEdgeLabelRenderer<GUINode, GUILink>() {
        public void labelEdge(RenderContext<GUINode, GUILink> rc, Layout<GUINode, GUILink> layout, GUILink e,
                String label) {
            if (callback.getVisualizationState().isCanvasShowLinkLabels())
                super.labelEdge(rc, layout, e, e.getLabel());
        }
    });
    vv.setEdgeToolTipTransformer(link -> link.getToolTip());
    vv.getRenderContext().setEdgeShapeTransformer(
            c -> c.element.isShownSeparated() ? originalEdgeShapeTransformer.transform(c)
                    : new Line2D.Float(0.0f, 0.0f, 1.0f, 0.0f));

    // Background controller
    this.paintableAssociatedToBackgroundImage = null;

    gm = new PluggableGraphMouse();
    vv.setGraphMouse(gm);

    scalingControl = new LayoutScalingControl();
    ITopologyCanvasPlugin scalingPlugin = new ScalingCanvasPlugin(scalingControl, MouseEvent.NOBUTTON);
    addPlugin(scalingPlugin);

    vv.setOpaque(false);
    vv.setBackground(new Color(0, 0, 0, 0));

    this.updateInterLayerDistanceInNpCoordinates(callback.getVisualizationState().getInterLayerSpaceInPixels());

    //        reset();
}

From source file:edu.uci.ics.jung.algorithms.layout.FRLayout.java

protected synchronized void calcPositions(V v) {
    FRVertexData fvd = getFRData(v);/*from w  ww  .  j  a  va  2  s. c o m*/
    if (fvd == null)
        return;
    Point2D xyd = transform(v);
    double deltaLength = Math.max(EPSILON, fvd.norm());

    double newXDisp = fvd.getX() / deltaLength * Math.min(deltaLength, temperature);

    if (Double.isNaN(newXDisp)) {
        throw new IllegalArgumentException("Unexpected mathematical result in FRLayout:calcPositions [xdisp]");
    }

    double newYDisp = fvd.getY() / deltaLength * Math.min(deltaLength, temperature);
    xyd.setLocation(xyd.getX() + newXDisp, xyd.getY() + newYDisp);

    double borderWidth = getSize().getWidth() / 50.0;
    double newXPos = xyd.getX();
    if (newXPos < borderWidth) {
        newXPos = borderWidth + Math.random() * borderWidth * 2.0;
    } else if (newXPos > (getSize().getWidth() - borderWidth)) {
        newXPos = getSize().getWidth() - borderWidth - Math.random() * borderWidth * 2.0;
    }

    double newYPos = xyd.getY();
    if (newYPos < borderWidth) {
        newYPos = borderWidth + Math.random() * borderWidth * 2.0;
    } else if (newYPos > (getSize().getHeight() - borderWidth)) {
        newYPos = getSize().getHeight() - borderWidth - Math.random() * borderWidth * 2.0;
    }

    xyd.setLocation(newXPos, newYPos);
}

From source file:com.wasteofplastic.beaconz.Beaconz.java

/**
 * Creates the corner-most beaconz so that the map can be theoretically be covered entirely (almost)
 */// w  w w.ja v  a2s .  co m
private void createCorners() {

    // Check corners
    Set<Point2D> corners = new HashSet<Point2D>();
    int xMin = Settings.xCenter - (Settings.borderSize / 2) + 2;
    int xMax = Settings.xCenter + (Settings.borderSize / 2) - 3;
    int zMin = Settings.zCenter - (Settings.borderSize / 2) + 2;
    int zMax = Settings.zCenter + (Settings.borderSize / 2) - 3;
    corners.add(new Point2D.Double(xMin, zMin));
    corners.add(new Point2D.Double(xMin, zMax));
    corners.add(new Point2D.Double(xMax, zMin));
    corners.add(new Point2D.Double(xMax, zMax));
    for (Point2D point : corners) {
        if (!register.isNearBeacon(point, 5)) {
            Block b = getBeaconzWorld().getHighestBlockAt((int) point.getX(), (int) point.getY());
            while (b.getType().equals(Material.AIR) || b.getType().equals(Material.LEAVES)
                    || b.getType().equals(Material.LEAVES_2)) {
                if (b.getY() == 0) {
                    // Oops, nothing here
                    break;
                }
                b = b.getRelative(BlockFace.DOWN);
            }
            if (b.getY() > 3) {
                // Create a beacon
                //Bukkit.getLogger().info("DEBUG: made beacon at " + b.getLocation());
                b.setType(Material.BEACON);
                // Register the beacon
                register.addBeacon(null, b.getLocation());
                // Add the capstone
                b.getRelative(BlockFace.UP).setType(Material.OBSIDIAN);
                // Create the pyramid
                b = b.getRelative(BlockFace.DOWN);

                // All diamond blocks for now
                b.setType(Material.DIAMOND_BLOCK);
                b.getRelative(BlockFace.SOUTH).setType(Material.DIAMOND_BLOCK);
                b.getRelative(BlockFace.SOUTH_EAST).setType(Material.DIAMOND_BLOCK);
                b.getRelative(BlockFace.SOUTH_WEST).setType(Material.DIAMOND_BLOCK);
                b.getRelative(BlockFace.EAST).setType(Material.DIAMOND_BLOCK);
                b.getRelative(BlockFace.WEST).setType(Material.DIAMOND_BLOCK);
                b.getRelative(BlockFace.NORTH).setType(Material.DIAMOND_BLOCK);
                b.getRelative(BlockFace.NORTH_EAST).setType(Material.DIAMOND_BLOCK);
                b.getRelative(BlockFace.NORTH_WEST).setType(Material.DIAMOND_BLOCK);
            }
        }
    }
}

From source file:com.github.lucapino.sheetmaker.renderer.JavaTemplateRenderer.java

public void drawString(Graphics g, String text, RectangularShape bounds, Align align, double angle,
        boolean multiline) {
    Graphics2D g2 = (Graphics2D) g;
    Font font = g2.getFont();/*from  ww  w  . jav a 2  s.  c o m*/
    if (angle != 0) {
        g2.setFont(font.deriveFont(AffineTransform.getRotateInstance(Math.toRadians(angle))));
    }

    Rectangle2D sSize = g2.getFontMetrics().getStringBounds(text, g2);
    Point2D pos = getPoint(bounds, align);
    double x = pos.getX();
    double y = pos.getY() + sSize.getHeight();

    switch (align) {
    case TopCenter:
    case BottomCenter:
    case Center:
        x -= (sSize.getWidth() / 2);
        break;
    case TopRight:
    case MiddleRight:
    case BottomRight:
        x -= (sSize.getWidth());
        break;
    case BottomLeft:
    case MiddleLeft:
    case TopLeft:
        break;
    }
    if (multiline) {
        // Create a new LineBreakMeasurer from the paragraph.
        // It will be cached and re-used.
        //if (lineMeasurer == null) {
        AttributedCharacterIterator paragraph = new AttributedString(text).getIterator();
        paragraphStart = paragraph.getBeginIndex();
        paragraphEnd = paragraph.getEndIndex();
        FontRenderContext frc = g2.getFontRenderContext();
        lineMeasurer = new LineBreakMeasurer(paragraph, frc);
        //}

        // Set break width to width of Component.
        float breakWidth = (float) bounds.getWidth();
        float drawPosY = (float) y;
        // Set position to the index of the first character in the paragraph.
        lineMeasurer.setPosition(paragraphStart);

        // Get lines until the entire paragraph has been displayed.
        while (lineMeasurer.getPosition() < paragraphEnd) {

            // Retrieve next layout. A cleverer program would also cache
            // these layouts until the component is re-sized.
            TextLayout layout = lineMeasurer.nextLayout(breakWidth);

            // Compute pen x position. If the paragraph is right-to-left we
            // will align the TextLayouts to the right edge of the panel.
            // Note: this won't occur for the English text in this sample.
            // Note: drawPosX is always where the LEFT of the text is placed.
            float drawPosX = layout.isLeftToRight() ? (float) x : (float) x + breakWidth - layout.getAdvance();

            // Move y-coordinate by the ascent of the layout.
            drawPosY += layout.getAscent();

            // Draw the TextLayout at (drawPosX, drawPosY).
            layout.draw(g2, drawPosX, drawPosY);

            // Move y-coordinate in preparation for next layout.
            drawPosY += layout.getDescent() + layout.getLeading();
        }
    } else {
        g2.drawString(text, (float) x, (float) y);
    }
    g2.setFont(font);
}

From source file:boundary.GraphPane.java

private Node addThresholdSlider(float min, float max) {
    HBox hBox = new HBox();

    hBox.setPadding(new Insets(15, 12, 15, 12));
    hBox.setStyle("-fx-background-color: #66FFFF;");

    Label lblThreshold = new Label("Threshold: ");
    lblThreshold.setPrefSize(100, 20);// w  w  w  .  j a va 2  s.  co  m

    Label lblValue = new Label("Value: ");
    lblValue.setPrefSize(50, 20);
    TextField tfValue = new TextField(String.valueOf(min));

    Slider thresholdSlider = new Slider();
    thresholdSlider.setMin(Math.floor(min));
    thresholdSlider.setMax(Math.ceil(max));
    thresholdSlider.setMajorTickUnit(Math.ceil((max - min) / 5));
    thresholdSlider.setMinorTickCount(1);
    thresholdSlider.setBlockIncrement(1);
    thresholdSlider.setSnapToTicks(true);
    thresholdSlider.setShowTickMarks(true);

    thresholdSlider.valueProperty().addListener(new ChangeListener<Number>() {

        @Override
        public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {

            edgePredicate.setThreshold(newValue.floatValue());
            vertexPredicate.setThreshold(newValue.floatValue());

            vv.repaint();

            tfValue.setText(String.format(Locale.US, "%.2f", newValue.floatValue()));

        }
    });

    tfValue.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {

        @Override
        public void handle(KeyEvent event) {
            float value;

            try {
                value = Float.parseFloat(tfValue.getText());
            } catch (Exception ex) {
                value = 0;
            }
            edgePredicate.setThreshold(value);
            vertexPredicate.setThreshold(value);

            vv.repaint();

            thresholdSlider.setValue(value);

        }
    });

    Label lblSearch = new Label("Search: ");
    lblSearch.setPrefSize(70, 20);

    TextField tf = new TextField();

    tf.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {

        @Override
        public void handle(KeyEvent event) {
            String toFind = tf.getText().toLowerCase();

            for (NodeInfo nodeInfo : nodesHighlighted)
                nodeInfo.setHighlighted(false);

            if (nodesHighlighted.size() > 0) {
                nodesHighlighted.clear();
                vv.repaint();
            }

            if (toFind.length() > 2) {
                for (NodeInfo nodeInfo : nodes.values()) {
                    if (nodeInfo.getUserData().toLowerCase().contains((toFind))) {
                        nodeInfo.setHighlighted(true);
                        nodesHighlighted.add(nodeInfo);
                    }
                }

                if (nodesHighlighted.size() == 1) {
                    Layout<String, String> layout = vv.getGraphLayout();
                    Point2D q = layout.transform(nodesHighlighted.get(0).id);
                    Point2D lvc = vv.getRenderContext().getMultiLayerTransformer()
                            .inverseTransform(vv.getCenter());
                    final double dx = (lvc.getX() - q.getX()) / 10;
                    final double dy = (lvc.getY() - q.getY()) / 10;

                    Runnable animator = new Runnable() {

                        public void run() {
                            for (int i = 0; i < 10; i++) {
                                vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT)
                                        .translate(dx, dy);
                                try {
                                    Thread.sleep(100);
                                } catch (InterruptedException ex) {
                                }
                            }
                        }
                    };

                    Thread thread = new Thread(animator);
                    thread.start();
                }
                vv.repaint();
            }
        }
    });

    hBox.getChildren().addAll(lblThreshold, thresholdSlider, lblValue, tfValue, lblSearch, tf);

    return hBox;
}