Java Code Examples for javafx.scene.Node#sceneToLocal()

The following examples show how to use javafx.scene.Node#sceneToLocal() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ADCCanvasView.java    From arma-dialog-creator with MIT License 7 votes vote down vote up
@Override
public void handle(MouseEvent event) {
	//use this so that when the mouse moves over the canvas and something in canvas controls has focus, the key presses
	//and mouse events are sent to the canvas rather than the focuses control
	canvasView.focusToCanvas(event.getTarget() == canvasView.uiCanvasEditor.getCanvas());

	double sceneX = event.getSceneX();
	double sceneY = event.getSceneY();
	for (Node node : canvasView.notificationPane.getContentPane().getChildren()) {
		Point2D point2D = node.sceneToLocal(sceneX, sceneY);
		if (node.contains(point2D)) {
			canvasView.notificationPane.getContentPane().setMouseTransparent(false);
			return;
		}
	}
	canvasView.notificationPane.getContentPane().setMouseTransparent(true);

}
 
Example 2
Source File: RFXComponentFactory.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
public RFXComponent findRawRComponent(Node source, Point2D point, IJSONRecorder recorder) {
    for (IRFXComponentFinder entry : entries) {
        Class<? extends RFXComponent> k = entry.get(source);
        if (k == null) {
            continue;
        }
        try {
            Constructor<? extends RFXComponent> cons = k.getConstructor(Node.class, JSONOMapConfig.class, Point2D.class,
                    IJSONRecorder.class);
            if (point != null) {
                point = source.sceneToLocal(point);
            }
            return cons.newInstance(source, omapConfig, point, recorder);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    System.out.println("RFXComponentFactory.findRawRComponent(" + source + "): Could not find rcomponent");
    return null;
}
 
Example 3
Source File: RFXComponentFactory.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
public RFXComponent findRCellComponent(Node source, Point2D point, IJSONRecorder recorder) {
    if (source == null)
        return null;
    for (IRFXComponentFinder entry : entries) {
        Class<? extends RFXComponent> k = entry.get(source);
        if (k == null) {
            continue;
        }
        try {
            Constructor<? extends RFXComponent> cons = k.getConstructor(Node.class, JSONOMapConfig.class, Point2D.class,
                    IJSONRecorder.class);
            if (point != null) {
                point = source.sceneToLocal(point);
            }
            RFXComponent newInstance = cons.newInstance(source, omapConfig, point, recorder);
            if (newInstance instanceof RFXUnknownComponent || newInstance instanceof RFXIgnoreComponent)
                return null;
            return newInstance;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}
 
Example 4
Source File: UtilitiesJavaFX.java    From JavaFXSmartGraph with MIT License 5 votes vote down vote up
/**
 * Determines the closest node that resides in the x,y scene position, if any.
 * <br>
 * Obtained from: http://fxexperience.com/2016/01/node-picking-in-javafx/
 * 
 * @param node      parent node
 * @param sceneX    x-coordinate of picking point
 * @param sceneY    y-coordinate of picking point
 * 
 * @return          topmost node containing (sceneX, sceneY) point
 */
public static Node pick(Node node, double sceneX, double sceneY) {
    Point2D p = node.sceneToLocal(sceneX, sceneY, true /* rootScene */);

    // check if the given node has the point inside it, or else we drop out
    if (!node.contains(p)) {
        return null;
    }

    // at this point we know that _at least_ the given node is a valid
    // answer to the given point, so we will return that if we don't find
    // a better child option
    if (node instanceof Parent) {
        // we iterate through all children in reverse order, and stop when we find a match.
        // We do this as we know the elements at the end of the list have a higher
        // z-order, and are therefore the better match, compared to children that
        // might also intersect (but that would be underneath the element).
        Node bestMatchingChild = null;
        List<Node> children = ((Parent) node).getChildrenUnmodifiable();
        for (int i = children.size() - 1; i >= 0; i--) {
            Node child = children.get(i);
            p = child.sceneToLocal(sceneX, sceneY, true /* rootScene */);
            if (child.isVisible() && !child.isMouseTransparent() && child.contains(p)) {
                bestMatchingChild = child;
                break;
            }
        }

        if (bestMatchingChild != null) {
            return pick(bestMatchingChild, sceneX, sceneY);
        }
    }

    return node;
}
 
Example 5
Source File: WSRecorder.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
@Override
public void recordRawMouseEvent(final RFXComponent r, MouseEvent e) {
    final JSONObject event = new JSONObject();
    event.put("type", "click_raw");
    int button = e.getButton() == MouseButton.PRIMARY ? java.awt.event.MouseEvent.BUTTON1 : java.awt.event.MouseEvent.BUTTON3;
    event.put("button", button);
    event.put("clickCount", e.getClickCount());
    event.put("modifiersEx", buildModifiersText(e));
    Node source = (Node) e.getSource();
    Node target = r.getComponent();
    Point2D sts = source.localToScene(new Point2D(e.getX(), e.getY()));
    Point2D tts = target.sceneToLocal(sts);
    event.put("x", tts.getX());
    event.put("y", tts.getY());
    final JSONObject o = new JSONObject();
    o.put("event", event);
    fill(r, o);
    if (e.getClickCount() == 1) {
        clickTimer = new Timer();
        clickTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                sendRecordMessage(o);
            }
        }, timerinterval.intValue());
    } else if (e.getClickCount() == 2) {
        if (clickTimer != null) {
            clickTimer.cancel();
            clickTimer = null;
        }
        sendRecordMessage(o);
    }
}
 
Example 6
Source File: NodeUtils.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Performs picking on the scene graph beginning at the specified root node
 * and processing its transitive children.
 *
 * @param sceneX
 *            The x-coordinate of the position to pick nodes at, interpreted
 *            in scene coordinate space.
 * @param sceneY
 *            The y-coordinate of the position to pick nodes at, interpreted
 *            in scene coordinate space.
 * @param root
 *            The root node at which to start with picking
 * @return A list of {@link Node}s which contain the the given coordinate.
 */
public static List<Node> getNodesAt(Node root, double sceneX,
		double sceneY) {
	List<Node> picked = new ArrayList<>();

	// start with given root node
	List<Node> nodes = new ArrayList<>();
	nodes.add(root);

	while (!nodes.isEmpty()) {
		Node current = nodes.remove(0);
		// transform to local coordinates
		Point2D pLocal = current.sceneToLocal(sceneX, sceneY);
		// check if bounds contains (necessary to find children in mouse
		// transparent regions)
		if (!current.isMouseTransparent()
				&& current.getBoundsInLocal().contains(pLocal)) {
			// check precisely
			if (current.contains(pLocal)) {
				picked.add(0, current);
			}
			// test all children, too
			if (current instanceof Parent) {
				nodes.addAll(0,
						((Parent) current).getChildrenUnmodifiable());
			}
		}
	}
	return picked;
}
 
Example 7
Source File: MarqueeOnDragHandler.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void endDrag(MouseEvent e, Dimension delta) {
	if (invalidGesture) {
		return;
	}

	// compute bounding box in scene coordinates
	IRootPart<? extends Node> root = getHost().getRoot();
	Node rootVisual = root.getVisual();
	endPosInRoot = rootVisual.sceneToLocal(e.getSceneX(), e.getSceneY());
	Point2D start = rootVisual.localToScene(startPosInRoot);
	Point2D end = rootVisual.localToScene(endPosInRoot);
	double[] bbox = bbox(start, end);

	// find nodes contained in bbox
	List<Node> nodes = findContainedNodes(rootVisual.getScene().getRoot(),
			bbox[0], bbox[1], bbox[2], bbox[3]);

	// find content parts for contained nodes
	List<IContentPart<? extends Node>> parts = getParts(nodes);

	// filter out all parts that are not selectable
	Iterator<IContentPart<? extends Node>> it = parts.iterator();
	while (it.hasNext()) {
		if (!it.next().isSelectable()) {
			it.remove();
		}
	}

	// select the selectable parts contained within the marquee area
	try {
		root.getViewer().getDomain().execute(
				new SelectOperation(root.getViewer(), parts),
				new NullProgressMonitor());
	} catch (ExecutionException e1) {
		throw new IllegalStateException(e1);
	}
	removeFeedback();
}
 
Example 8
Source File: ChopBoxStrategy.java    From gef with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Computes the anchorage reference position in scene coordinates, based on
 * the given anchorage geometry.
 *
 * @see #computeAnchorageReferencePointInLocal(Node, IGeometry, Point)
 * @param anchorage
 *            The anchorage visual.
 * @param geometryInLocal
 *            The anchorage geometry within the coordinate system of the
 *            anchorage visual.
 * @param anchoredReferencePointInScene
 *            The reference {@link Point} of the anchored for which the
 *            anchorage reference {@link Point} is to be determined.
 * @return The anchorage reference position in scene coordinates or
 *         <code>null</code> if the computation should rather fall back to
 *         the nearest projection.
 */
protected Point computeAnchorageReferencePointInScene(Node anchorage,
		IGeometry geometryInLocal, Point anchoredReferencePointInScene) {
	Point2D anchoredReferencePointInAnchorageLocal = anchorage.sceneToLocal(
			anchoredReferencePointInScene.x,
			anchoredReferencePointInScene.y);
	Point anchorageReferencePointInLocal = computeAnchorageReferencePointInLocal(
			anchorage, geometryInLocal,
			new Point(anchoredReferencePointInAnchorageLocal.getX(),
					anchoredReferencePointInAnchorageLocal.getY()));
	if (anchorageReferencePointInLocal == null) {
		return null;
	}
	return NodeUtils.localToScene(anchorage,
			anchorageReferencePointInLocal);
}
 
Example 9
Source File: ResizeTranslateFirstAnchorageOnHandleDragHandler.java    From gef with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void drag(MouseEvent e, Dimension delta) {
	// guard against uninitialized access
	if (invalidGesture) {
		return;
	}

	// compute end point
	Node visual = getTargetPart().getVisual();
	Point newEndScene = new Point(e.getSceneX(), e.getSceneY());

	// compute delta in scene
	Point deltaInScene = new Point(newEndScene.x - initialPointerLocation.x,
			newEndScene.y - initialPointerLocation.y);

	// apply delta to the moved vertex
	Point newVertex = initialVertex.getTranslated(deltaInScene);

	// snap the moved vertex (unless isPrecise(e))
	Point snappedVertex = newVertex;
	if (snapToSupport != null) {
		if (!isPrecise(e)) {
			snappedVertex.translate(snapToSupport
					.snap(new Dimension(deltaInScene.x, deltaInScene.y)));
		} else {
			snapToSupport.clearSnappingFeedback();
		}
	}

	// compute delta between initial and snapped vertex
	Point2D startLocal = visual.sceneToLocal(initialVertex.x,
			initialVertex.y);
	Point2D endLocal = visual.sceneToLocal(snappedVertex.x,
			snappedVertex.y);

	// compute delta in local coordinates
	double deltaX = endLocal.getX() - startLocal.getX();
	double deltaY = endLocal.getY() - startLocal.getY();

	// segment index determines logical position (0 = top left, 1 = top
	// right, 2 = bottom right, 3 = bottom left)
	int segment = getHost().getSegmentIndex();

	// determine resize in local coordinates
	double ldw, ldh;
	if (segment == 1 || segment == 2) {
		// right side
		ldw = deltaX;
	} else {
		// left side
		ldw = -deltaX;
	}
	if (segment == 2 || segment == 3) {
		// bottom side
		ldh = deltaY;
	} else {
		// top side
		ldh = -deltaY;
	}

	// XXX: Resize before querying the applicable delta, so that the minimum
	// size is respected.
	getResizePolicy().resize(ldw, ldh);
	Dimension applicableDelta = new Dimension(
			getResizePolicy().getDeltaWidth(),
			getResizePolicy().getDeltaHeight());

	// Only apply translation if possible, i.e. if the resize cannot be
	// applied in total, the translation can probably not be applied in
	// total as well.
	if (applicableDelta.width != ldw) {
		deltaX = applicableDelta.width;
		if (segment == 0 || segment == 3) {
			deltaX = -deltaX;
		}
	}
	if (applicableDelta.height != ldh) {
		deltaY = applicableDelta.height;
		if (segment == 0 || segment == 1) {
			deltaY = -deltaY;
		}
	}

	// compute (local) translation
	double ldx = segment == 0 || segment == 3 ? deltaX : 0;
	double ldy = segment == 0 || segment == 1 ? deltaY : 0;

	// apply translation
	getTransformPolicy().setPreTranslate(translationIndex, ldx, ldy);
}
 
Example 10
Source File: SnapToGrid.java    From gef with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Snaps the given position (in scene coordinates) to a grid position (in
 * scene coordinates). The grid positions are specified by the given
 * {@link GridModel} and the given cell size fractions.
 *
 * @param sceneX
 *            The x-coordinate of the current position (in scene
 *            coordinates).
 * @param sceneY
 *            The y-coordinate of the current position (in scene
 *            coordinates).
 * @param gridModel
 *            The {@link GridModel} that specifies the grid positions.
 * @param gridCellWidthFraction
 *            The cell width fraction that determines if the x-coordinate is
 *            snapped to full (1.0), halve (0.5), etc. grid positions.
 * @param gridCellHeightFraction
 *            The cell height fraction that determines if the y-coordinate
 *            is snapped to full (1.0), halve (0.5), etc. grid positions.
 * @param gridLocalVisual
 *            A visual within the coordinate system where grid positions are
 *            at <code>(n * grid-cell-width, m * grid-cell-height)</code>.
 * @return The resulting snapped position in scene coordinates.
 */
protected Point snapToGrid(final double sceneX, final double sceneY,
		GridModel gridModel, final double gridCellWidthFraction,
		final double gridCellHeightFraction, Node gridLocalVisual) {
	// transform to grid local coordinates
	Point2D gridLocalPosition = gridLocalVisual.sceneToLocal(sceneX,
			sceneY);
	// snap to (nearest) grid point (add 0.5 so that the nearest grid
	// position is computed)
	double gcw = gridCellWidthFraction * gridModel.getGridCellWidth();
	double nearest = gridLocalPosition.getX() > 0 ? 0.5 : -0.5;
	int xs = (int) (gridLocalPosition.getX() / gcw + nearest);
	double gch = gridCellHeightFraction * gridModel.getGridCellHeight();
	nearest = gridLocalPosition.getY() > 0 ? 0.5 : -0.5;
	int ys = (int) (gridLocalPosition.getY() / gch + nearest);
	double nx = xs * gcw;
	double ny = ys * gch;
	// transform to scene coordinates
	Point2D newPositionInScene = gridLocalVisual.localToScene(nx, ny);
	return new Point(newPositionInScene.getX(), newPositionInScene.getY());
}
 
Example 11
Source File: ResizeTransformSelectedOnHandleDragHandler.java    From gef with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void drag(MouseEvent e, Dimension delta) {
	if (invalidGesture) {
		return;
	}
	if (selectionBounds == null) {
		return;
	}
	if (targetParts.isEmpty()) {
		return;
	}

	// snap to grid
	// FIXME: apply resize-transform first, then snap the moved vertex to
	// the next grid position and update the values

	// TODO
	Point newEndPointInScene = isPrecise(e)
			? new Point(e.getSceneX(), e.getSceneY())
			: new Point(e.getSceneX(), e.getSceneY());

	// update selection bounds
	Rectangle sel = updateSelectionBounds(newEndPointInScene);

	// update target parts
	for (IContentPart<? extends Node> targetPart : targetParts) {
		// compute initial and new bounds for this target
		Bounds initialBounds = getBounds(selectionBounds, targetPart);
		Bounds newBounds = getBounds(sel, targetPart);

		// System.out.println(targetPart.getClass().getSimpleName()
		// + " bounds change from " + initialBounds.getMinX() + ", "
		// + initialBounds.getMinY() + " : " + initialBounds.getWidth()
		// + " x " + initialBounds.getHeight() + " to "
		// + newBounds.getMinX() + ", " + newBounds.getMinY() + " : "
		// + newBounds.getWidth() + " x " + newBounds.getHeight()
		// + ".");

		// compute translation in scene coordinates
		double dx = newBounds.getMinX() - initialBounds.getMinX();
		double dy = newBounds.getMinY() - initialBounds.getMinY();

		// transform translation to parent coordinates
		Node visual = targetPart.getVisual();
		Point2D originInParent = visual.getParent().sceneToLocal(0, 0);
		Point2D deltaInParent = visual.getParent().sceneToLocal(dx, dy);
		dx = deltaInParent.getX() - originInParent.getX();
		dy = deltaInParent.getY() - originInParent.getY();

		// apply translation
		getTransformPolicy(targetPart)
				.setPostTranslate(translateIndices.get(targetPart), dx, dy);

		// check if we can resize the part
		AffineTransform affineTransform = getTransformPolicy(targetPart)
				.getCurrentTransform();
		if (affineTransform.getRotation().equals(Angle.fromDeg(0))) {
			// no rotation => resize possible
			// TODO: special case 90 degree rotations
			double dw = newBounds.getWidth() - initialBounds.getWidth();
			double dh = newBounds.getHeight() - initialBounds.getHeight();

			// System.out.println(
			// "delta size in scene: " + dw + ", " + dh + ".");

			Point2D originInLocal = visual.sceneToLocal(newBounds.getMinX(),
					newBounds.getMinY());
			Point2D dstInLocal = visual.sceneToLocal(
					newBounds.getMinX() + dw, newBounds.getMinY() + dh);
			dw = dstInLocal.getX() - originInLocal.getX();
			dh = dstInLocal.getY() - originInLocal.getY();

			// System.out.println(
			// "delta size in local: " + dw + ", " + dh + ".");

			getResizePolicy(targetPart).resize(dw, dh);
		} else {
			// compute scaling based on bounds change
			double sx = newBounds.getWidth() / initialBounds.getWidth();
			double sy = newBounds.getHeight() / initialBounds.getHeight();
			// apply scaling
			getTransformPolicy(targetPart)
					.setPostScale(scaleIndices.get(targetPart), sx, sy);
		}
	}
}