javafx.geometry.Point2D Java Examples

The following examples show how to use javafx.geometry.Point2D. 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: FXColorPicker.java    From gef with Eclipse Public License 2.0 7 votes vote down vote up
/**
 * Draws a color wheel into the given {@link WritableImage}, starting at the
 * given offsets, in the given size (in pixel).
 *
 * @param image
 *            The {@link WritableImage} in which the color wheel is drawn.
 * @param offsetX
 *            The horizontal offset (in pixel).
 * @param offsetY
 *            The vertical offset (in pixel).
 * @param size
 *            The size (in pixel).
 */
private void renderColorWheel(WritableImage image, int offsetX, int offsetY,
		int size) {
	PixelWriter px = image.getPixelWriter();
	double radius = size / 2;
	Point2D mid = new Point2D(radius, radius);
	for (int y = 0; y < size; y++) {
		for (int x = 0; x < size; x++) {
			double d = mid.distance(x, y);
			if (d <= radius) {
				// compute hue angle
				double angleRad = d == 0 ? 0
						: Math.atan2(y - mid.getY(), x - mid.getX());
				// compute saturation depending on distance to
				// middle
				// ([0;1])
				double sat = d / radius;
				Color color = Color.hsb(angleRad * 180 / Math.PI, sat, 1);
				px.setColor(offsetX + x, offsetY + y, color);
			} else {
				px.setColor(offsetX + x, offsetY + y, Color.TRANSPARENT);
			}
		}
	}
}
 
Example #3
Source File: GoogleMap.java    From GMapsFX with Apache License 2.0 6 votes vote down vote up
/**
     * Returns the screen point for the provided LatLong. Note: Unexpected
     * results can be obtained if this method is called as a result of a zoom
     * change, as the zoom event is fired before the bounds are updated, and
     * bounds need to be used to obtain the answer!
     * <p>
     * One workaround is to only operate off bounds_changed events.
     *
     * @param loc
     * @return
     */
    public Point2D fromLatLngToPoint(LatLong loc) {
//        System.out.println("GoogleMap.fromLatLngToPoint loc: " + loc);
        Projection proj = getProjection();
        //System.out.println("map.fromLatLngToPoint Projection: " + proj);
        LatLongBounds llb = getBounds();
//        System.out.println("GoogleMap.fromLatLngToPoint Bounds: " + llb);

        GMapPoint topRight = proj.fromLatLngToPoint(llb.getNorthEast());
//        System.out.println("GoogleMap.fromLatLngToPoint topRight: " + topRight);
        GMapPoint bottomLeft = proj.fromLatLngToPoint(llb.getSouthWest());
//        System.out.println("GoogleMap.fromLatLngToPoint bottomLeft: " + bottomLeft);

        double scale = Math.pow(2, getZoom());
        GMapPoint worldPoint = proj.fromLatLngToPoint(loc);
//        System.out.println("GoogleMap.fromLatLngToPoint worldPoint: " + worldPoint);

        double x = (worldPoint.getX() - bottomLeft.getX()) * scale;
        double y = (worldPoint.getY() - topRight.getY()) * scale;

//        System.out.println("GoogleMap.fromLatLngToPoint x: " + x + " y: " + y);
        return new Point2D(x, y);
    }
 
Example #4
Source File: Rubberband.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
private void handleStart(final MouseEvent event)
{
    if (! event.isPrimaryButtonDown())
        return;
    active = true;

    // Event originates from a node that allows 'clicking' beyond the
    // model elements, i.e. the size of the 'parent'.
    // The 'parent', however, may be scrolled, and the rubber band needs
    // to show up in the 'parent', so convert coordinates
    // from event to the parent:
    final Point2D in_parent = parent.sceneToLocal(event.getSceneX(), event.getSceneY());
    x0 = in_parent.getX();
    y0 = in_parent.getY();
    rect.setX(x0);
    rect.setY(y0);
    rect.setWidth(1);
    rect.setHeight(1);
    parent.getChildren().add(rect);
    event.consume();
}
 
Example #5
Source File: FXNonApplicationThreadRule.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Fires a newly created {@link MouseEvent} of type
 * {@link MouseEvent#MOUSE_MOVED} to the given target {@link Node}.
 *
 * @param sceneX
 *            The final x-coordinate (in scene) for the drag.
 * @param sceneY
 *            The final y-coordinate (in scene) for the drag.
 * @param mods
 *            The {@link Modifiers} for the {@link MouseEvent}.
 */
public void mouseMove(final Node target, final double sceneX, final double sceneY, final Modifiers mods) {
	waitForIdle();
	// save mouse interaction data
	lastMouseInteraction = new MouseInteraction();
	lastMouseInteraction.target = target;
	lastMouseInteraction.sceneX = sceneX;
	lastMouseInteraction.sceneY = sceneY;
	run(() -> {
		Point2D local = target.sceneToLocal(sceneX, sceneY);
		Point2D screen = target.localToScreen(local.getX(), local.getY());
		fireEvent(target,
				new MouseEvent(target, target, MouseEvent.MOUSE_MOVED, local.getX(), local.getY(), screen.getX(),
						screen.getY(), MouseButton.NONE, 0, mods.shift, mods.control, mods.alt, mods.meta, false,
						false, false, false, false, false, new PickResult(target, sceneX, sceneY)));
	});
	waitForIdle();
}
 
Example #6
Source File: AnimatedTableRow.java    From mars-sim with GNU General Public License v3.0 6 votes vote down vote up
private void moveDataWithAnimation(final TableView<Person> sourceTable,
		final TableView<Person> destinationTable,
		final Pane commonTableAncestor, final TableRow<Person> row) {
	// Create imageview to display snapshot of row:
	final ImageView imageView = createImageView(row);
	// Start animation at current row:
	final Point2D animationStartPoint = row.localToScene(new Point2D(0, 0)); // relative to Scene
	final Point2D animationEndPoint = computeAnimationEndPoint(destinationTable); // relative to Scene
	// Set start location
	final Point2D startInRoot = commonTableAncestor.sceneToLocal(animationStartPoint); // relative to commonTableAncestor
	imageView.relocate(startInRoot.getX(), startInRoot.getY());
	// Create animation
	final Animation transition = createAndConfigureAnimation(
			sourceTable, destinationTable, commonTableAncestor, row,
			imageView, animationStartPoint, animationEndPoint);
	// add animated image to display
	commonTableAncestor.getChildren().add(imageView);
	// start animation
	transition.play();
}
 
Example #7
Source File: ConnectionSegment.java    From graph-editor with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new connection segment for the given start and end points.
 *
 * @param start the point where the segment starts
 * @param end the point where the segment ends
 * @param intersections the intersection-points of this segment with other connections
 */
public ConnectionSegment(final Point2D start, final Point2D end, final List<Double> intersections) {

    this.start = start;
    this.end = end;
    this.intersections = intersections;

    horizontal = start.getY() == end.getY();

    if (horizontal) {
        sign = start.getX() < end.getX() ? 1 : -1;
    } else {
        sign = start.getY() < end.getY() ? 1 : -1;
    }

    filterIntersections();
}
 
Example #8
Source File: FXNonApplicationThreadRule.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Fires a newly created {@link MouseEvent} of type
 * {@link MouseEvent#MOUSE_RELEASED} to the target {@link Node} of the last
 * mouse interaction.
 *
 * @param mods
 *            The {@link Modifiers} for the {@link MouseEvent}.
 */
public void mouseRelease(final Modifiers mods) {
	waitForIdle();
	run(() -> {
		Point2D local = lastMouseInteraction.target.sceneToLocal(lastMouseInteraction.sceneX,
				lastMouseInteraction.sceneY);
		Point2D screen = lastMouseInteraction.target.localToScreen(local.getX(), local.getY());
		fireEvent(lastMouseInteraction.target,
				new MouseEvent(lastMouseInteraction.target, lastMouseInteraction.target, MouseEvent.MOUSE_RELEASED,
						local.getX(), local.getY(), screen.getX(), screen.getY(), MouseButton.PRIMARY, 1,
						mods.shift, mods.control, mods.alt, mods.meta, false, false, false, false, false, false,
						new PickResult(lastMouseInteraction.target, lastMouseInteraction.sceneX,
								lastMouseInteraction.sceneY)));
	});
	waitForIdle();
}
 
Example #9
Source File: JavaFXElementPropertyAccessor.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
protected int getIndexAt(ListView<?> listView, Point2D point) {
    if (point == null) {
        return listView.getSelectionModel().getSelectedIndex();
    }
    point = listView.localToScene(point);
    Set<Node> lookupAll = getListCells(listView);
    ListCell<?> selected = null;
    for (Node cellNode : lookupAll) {
        Bounds boundsInScene = cellNode.localToScene(cellNode.getBoundsInLocal(), true);
        if (boundsInScene.contains(point)) {
            selected = (ListCell<?>) cellNode;
            break;
        }
    }
    if (selected == null) {
        return -1;
    }
    return selected.getIndex();
}
 
Example #10
Source File: BonusPlayerHandler.java    From FXGLGames with MIT License 6 votes vote down vote up
@Override
protected void onCollisionBegin(Entity bonus, Entity player) {
    BonusType type = (BonusType) bonus.getComponent(SubTypeComponent.class).getValue();
    fire(new BonusPickupEvent(BonusPickupEvent.ANY, type));

    bonus.getComponent(CollidableComponent.class).setValue(false);
    bonus.setUpdateEnabled(false);

    animationBuilder()
            .duration(Duration.seconds(0.66))
            .interpolator(Interpolators.ELASTIC.EASE_IN())
            .onFinished(bonus::removeFromWorld)
            .scale(bonus)
            .to(new Point2D(0, 0))
            .buildAndPlay();
}
 
Example #11
Source File: SimpleControl.java    From PreferencesFX with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the error message as tooltip for the matching control.
 *
 * @param below     The control needed for positioning the tooltip.
 * @param reference The control which gets the tooltip.
 */
@Override
protected void toggleTooltip(Node reference, Control below) {
  String fieldTooltip = field.getTooltip();

  if ((reference.isFocused() || reference.isHover())
      && (!fieldTooltip.equals("") || field.getErrorMessages().size() > 0)) {
    tooltip.setText((!fieldTooltip.equals("") ? fieldTooltip + "\n" : "")
        + String.join("\n", field.getErrorMessages()));

    if (tooltip.isShowing()) {
      return;
    }

    Point2D p = below.localToScene(0.0, 0.0);

    tooltip.show(
        reference.getScene().getWindow(),
        p.getX() + reference.getScene().getX() + reference.getScene().getWindow().getX(),
        p.getY() + reference.getScene().getY() + reference.getScene().getWindow().getY()
            + below.getHeight() + 5
    );
  } else {
    tooltip.hide();
  }
}
 
Example #12
Source File: TabsRepresentation.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
/** Compute 'insets'
 *
 *  <p>Determines where the tabs' content Pane
 *  is located relative to the bounds of the TabPane
 */
private void computeInsets()
{
    // Called with delay by refreshHack, may be invoked when already disposed
    if (jfx_node == null)
        return;
    // There is always at least one tab. All tabs have the same size.
    final Pane pane = (Pane)jfx_node.getTabs().get(0).getContent();
    final Point2D tabs_bounds = jfx_node.localToScene(0.0, 0.0);
    final Point2D pane_bounds = pane.localToScene(0.0, 0.0);
    final int[] insets = new int[] { (int)(pane_bounds.getX() - tabs_bounds.getX()),
            (int)(pane_bounds.getY() - tabs_bounds.getY()) };
    // logger.log(Level.INFO, "Insets: " + Arrays.toString(insets));
    if (insets[0] < 0  ||  insets[1] < 0)
    {
        logger.log(Level.WARNING, "Inset computation failed: TabPane at " + tabs_bounds + ", content pane at " + pane_bounds);
        insets[0] = insets[1] = 0;
    }
    model_widget.runtimePropInsets().setValue(insets);
}
 
Example #13
Source File: JointCreator.java    From graph-editor with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the new joint positions of the temporary joints.
 *
 * @return the list of positions of the temporary joints
 */
private List<Point2D> getNewJointPositions() {

    final SkinLookup skinLookup = graphEditor.getSkinLookup();
    final List<Point2D> allJointPositions = GeometryUtils.getJointPositions(connection, skinLookup);

    final Set<Integer> jointsToCleanUp = JointCleaner.findJointsToCleanUp(allJointPositions);

    final List<Point2D> newJointPositions = new ArrayList<>();

    for (int i = 0; i < allJointPositions.size(); i++) {
        if (!jointsToCleanUp.contains(i)) {
            newJointPositions.add(allJointPositions.get(i));
        }
    }

    return newJointPositions;
}
 
Example #14
Source File: BejeweledApp.java    From FXTutorials with MIT License 6 votes vote down vote up
public Jewel(Point2D point) {
    circle.setCenterX(SIZE / 2);
    circle.setCenterY(SIZE / 2);
    circle.setFill(colors[new Random().nextInt(colors.length)]);

    setTranslateX(point.getX() * SIZE);
    setTranslateY(point.getY() * SIZE);
    getChildren().add(circle);

    setOnMouseClicked(event -> {
        if (selected == null) {
            selected = this;
        }
        else {
            swap(selected, this);
            checkState();
            selected = null;
        }
    });
}
 
Example #15
Source File: Level2.java    From FXGLGames with MIT License 6 votes vote down vote up
@Override
public void init() {
    for (int y = 0; y < ENEMY_ROWS; y++) {
        for (int x = 0; x < ENEMIES_PER_ROW; x++) {
            double px = random(0, getAppWidth() - 100);
            double py = random(0, getAppHeight() / 2.0);

            Entity enemy = spawnEnemy(px, py);

            var a = animationBuilder()
                    .autoReverse(true)
                    .interpolator(Interpolators.ELASTIC.EASE_IN_OUT())
                    .repeatInfinitely()
                    .duration(Duration.seconds(1.0))
                    .translate(enemy)
                    .from(new Point2D(px, py))
                    .to(new Point2D(random(0, getAppWidth() - 100), random(0, getAppHeight() / 2.0)))
                    .build();

            animations.add(a);
            a.start();
        }
    }
}
 
Example #16
Source File: FXNonApplicationThreadRule.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Fires a newly created {@link MouseEvent} of type
 * {@link MouseEvent#MOUSE_PRESSED} to the target {@link Node} of the last mouse
 * interaction.
 *
 * @param mods
 *            The {@link Modifiers} for the {@link MouseEvent}.
 */
public void mousePress(final Modifiers mods) {
	waitForIdle();
	run(() -> {
		Point2D local = lastMouseInteraction.target.sceneToLocal(lastMouseInteraction.sceneX,
				lastMouseInteraction.sceneY);
		Point2D screen = lastMouseInteraction.target.localToScreen(local.getX(), local.getY());
		fireEvent(lastMouseInteraction.target,
				new MouseEvent(lastMouseInteraction.target, lastMouseInteraction.target, MouseEvent.MOUSE_PRESSED,
						local.getX(), local.getY(), screen.getX(), screen.getY(), MouseButton.PRIMARY, 1,
						mods.shift, mods.control, mods.alt, mods.meta, true, false, false, false, false, false,
						new PickResult(lastMouseInteraction.target, lastMouseInteraction.sceneX,
								lastMouseInteraction.sceneY)));
	});
	waitForIdle();
}
 
Example #17
Source File: RFXTableViewTest.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
@Test
public void selectAllRows() {
    TableView<?> tableView = (TableView<?>) getPrimaryStage().getScene().getRoot().lookup(".table-view");
    LoggingRecorder lr = new LoggingRecorder();
    Platform.runLater(() -> {
        tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        Point2D point = getPoint(tableView, 1, 1);
        RFXTableView rfxTableView = new RFXTableView(tableView, null, point, lr);
        rfxTableView.focusGained(null);
        tableView.getSelectionModel().selectRange(0, 5);
        rfxTableView.focusLost(null);
    });
    List<Recording> recordings = lr.waitAndGetRecordings(1);
    Recording recording = recordings.get(0);
    AssertJUnit.assertEquals("recordSelect", recording.getCall());
    AssertJUnit.assertEquals("all", recording.getParameters()[0]);
}
 
Example #18
Source File: JFXRepresentation.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/** Ctrl-Wheel zoom gesture help function
    *  Zoom work function
    */
   private void doWheelZoom(final double delta, final double x, final double y)
   {
       final double zoom = getZoom();
if (delta == 0)
    return;
       if (zoom >= ZOOM_MAX && delta > 0)
           return;
       if (zoom <= ZOOM_MIN && delta < 0)
           return;

       final double zoomFactor = delta > 0 ? ZOOM_FACTOR : 1 / ZOOM_FACTOR;
       double new_zoom = zoom * zoomFactor;
       new_zoom = new_zoom > ZOOM_MAX ? ZOOM_MAX : (new_zoom < ZOOM_MIN ? ZOOM_MIN : new_zoom);
       final double realFactor = new_zoom / zoom;

       Point2D scrollOffset = figureScrollOffset(scroll_body, model_root);

       // Set Zoom:
       // do not directly setValue(Double.toString(new_zoom * 100));
       // setText() only, otherwise it gets into an endless update due to getValue/setValue implementation in Editor. In Runtime was OK.
       // Drawback: return to a previous "combo driven" zoom level from any wheel level not possible directly (no value change in combo)
       setZoom(new_zoom);
       zoom_listener.accept(Integer.toString((int)(new_zoom * 100)) + " %");

       repositionScroller(scroll_body, model_root, realFactor, scrollOffset, new Point2D(x, y));
   }
 
Example #19
Source File: TriangulatedMesh.java    From FXyzLib with GNU General Public License v3.0 5 votes vote down vote up
private int getMiddle(int v1, Point2D p1, int v2, Point2D p2){
    String key = ""+Math.min(v1,v2)+"_"+Math.max(v1,v2);
    if(map.get(key)!=null){
        return map.get(key);
    }

    texCoord1.add(p1.add(p2).multiply(0.5f));

    map.put(key,index.get());
    return index.getAndIncrement();
}
 
Example #20
Source File: BreakoutFactory.java    From FXGLGames with MIT License 5 votes vote down vote up
@Spawns("bulletBall")
public Entity newBulletBall(SpawnData data) {
    Point2D dir = data.get("dir");

    return entityBuilder()
            .from(data)
            .type(BULLET_BALL)
            .bbox(new HitBox(BoundingShape.circle(64)))
            .view("ball.png")
            .collidable()
            .with(new ProjectileComponent(dir, 800))
            .scale(0.1, 0.1)
            .build();
}
 
Example #21
Source File: TestCanvasCreation.java    From latexdraw with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testDrawFreeHand() {
	final Point2D pos = point(canvas).query();
	Cmds.of(CmdFXVoid.of(() -> editing.setCurrentChoice(EditionChoice.FREE_HAND)),
		CmdFXVoid.of(() -> editing.getGroupParams().setInterval(1)),
		() -> drag(pos, MouseButton.PRIMARY).dropBy(100d, 200d)).execute();

	assertEquals(1, drawing.size());
	assertTrue(drawing.getShapeAt(0).orElseThrow() instanceof Freehand);
	assertEquals(100d, drawing.getShapeAt(0).orElseThrow().getWidth(), 1d);
	assertEquals(200d, drawing.getShapeAt(0).orElseThrow().getHeight(), 1d);

	assertEquals(-Canvas.getMargins() + canvas.screenToLocal(pos).getX(), drawing.getShapeAt(0).orElseThrow().getTopLeftPoint().getX(), 1d);
	assertEquals(-Canvas.getMargins() + canvas.screenToLocal(pos).getY(), drawing.getShapeAt(0).orElseThrow().getTopLeftPoint().getY(), 1d);
}
 
Example #22
Source File: JavaFXListViewElementScrollTest.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
@Test
public void scrollToItem() throws Throwable {
    ListView<?> listViewNode = (ListView<?>) getPrimaryStage().getScene().getRoot().lookup(".list-view");
    Platform.runLater(() -> listView.marathon_select("[\"Row 23\"]"));
    new Wait("Waiting for the point to be in viewport") {
        @Override
        public boolean until() {
            return getPoint(listViewNode, 22) != null;
        }
    };
    Point2D point = getPoint(listViewNode, 22);
    AssertJUnit.assertTrue(listViewNode.getBoundsInLocal().contains(point));
}
 
Example #23
Source File: MovablePane.java    From DeskChan with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void storePositionToStorage() {
	final String key = getCurrentPositionStorageKey();
	if (key != null) {
		Point2D pos = getPosition();
		Main.getProperties().put(key, pos.getX() + ";" + pos.getY());
	}
}
 
Example #24
Source File: SpaceRunnerApp.java    From FXGLGames with MIT License 5 votes vote down vote up
private void nextLevel() {
    uiTextLevel.setVisible(false);

    inc("level", +1);

    level = new Level();
    level.spawnNewWave();

    Text textLevel = getUIFactory().newText("Level " + geti("level"), Color.WHITE, 22);
    textLevel.setEffect(new DropShadow(7, Color.BLACK));
    textLevel.setOpacity(0);

    centerText(textLevel);
    textLevel.setTranslateY(250);

    addUINode(textLevel);

    animationBuilder()
            .interpolator(Interpolators.SMOOTH.EASE_OUT())
            .duration(Duration.seconds(1.66))
            .onFinished(() -> {
                animationBuilder()
                        .duration(Duration.seconds(1.66))
                        .interpolator(Interpolators.EXPONENTIAL.EASE_IN())
                        .onFinished(() -> {
                            removeUINode(textLevel);
                            uiTextLevel.setVisible(true);
                        })
                        .translate(textLevel)
                        .from(new Point2D(textLevel.getTranslateX(), textLevel.getTranslateY()))
                        .to(new Point2D(330, 540))
                        .buildAndPlay();
            })
            .fadeIn(textLevel)
            .buildAndPlay();
}
 
Example #25
Source File: HoverHandleContainerPart.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
protected void refreshHandleLocation(Node hostVisual) {
	// position vbox top-right next to the host
	Bounds hostBounds = hostVisual.getBoundsInParent();
	Parent parent = hostVisual.getParent();
	if (parent != null) {
		hostBounds = parent.localToScene(hostBounds);
	}
	Point2D location = getVisual().getParent()
			.sceneToLocal(hostBounds.getMaxX(), hostBounds.getMinY());
	getVisual().setLayoutX(location.getX());
	getVisual().setLayoutY(location.getY());
}
 
Example #26
Source File: AnimatedTableRow.java    From mars-sim with GNU General Public License v3.0 5 votes vote down vote up
private TranslateTransition createAndConfigureAnimation(
		final TableView<Person> sourceTable,
		final TableView<Person> destinationTable,
		final Pane commonTableAncestor, final TableRow<Person> row,
		final ImageView imageView, final Point2D animationStartPoint,
		Point2D animationEndPoint) {
	final TranslateTransition transition = new TranslateTransition(ANIMATION_DURATION, imageView);
	// At end of animation, actually move data, and remove animated image
	transition.setOnFinished(createAnimationFinishedHandler(sourceTable, destinationTable, commonTableAncestor, row.getItem(), imageView));
	// configure transition
	transition.setByX(animationEndPoint.getX() - animationStartPoint.getX()); // absolute translation, computed from coords relative to Scene
	transition.setByY(animationEndPoint.getY() - animationStartPoint.getY()); // absolute translation, computed from coords relative to Scene
	return transition;
}
 
Example #27
Source File: TailManager.java    From graph-editor with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Updates the tail position based on new cursor position.
 * 
 * @param the mouse event responsible for updating the position
 */
public void updatePosition(final MouseEvent event) {

    if (tailSkin != null && sourcePosition != null) {

        final Point2D cursorPosition = getScaledPosition(GeometryUtils.getCursorPosition(event, view));

        if (jointPositions != null) {
            tailSkin.draw(sourcePosition, cursorPosition, jointPositions);
        } else {
            tailSkin.draw(sourcePosition, cursorPosition);
        }
    }
}
 
Example #28
Source File: TestCanvasCreation.java    From latexdraw with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testDrawCircle() {
	final Point2D pos = point(canvas).query();
	Cmds.of(CmdFXVoid.of(() -> editing.setCurrentChoice(EditionChoice.CIRCLE)),
		() -> drag(pos, MouseButton.PRIMARY).dropBy(101d, 11d)).execute();

	assertEquals(1, drawing.size());
	assertTrue(drawing.getShapeAt(0).orElseThrow() instanceof Circle);
	assertEquals(202d, drawing.getShapeAt(0).orElseThrow().getWidth(), 0.00001d);
	assertEquals(202d, drawing.getShapeAt(0).orElseThrow().getHeight(), 0.00001d);
	assertEquals(-Canvas.getMargins() + canvas.screenToLocal(pos).getX() - 101d, drawing.getShapeAt(0).orElseThrow().getTopLeftPoint().getX(), 0.00001d);
	assertEquals(-Canvas.getMargins() + canvas.screenToLocal(pos).getY() - 101d, drawing.getShapeAt(0).orElseThrow().getTopLeftPoint().getY(), 0.00001d);
}
 
Example #29
Source File: RunnerComponent.java    From FXGLGames with MIT License 5 votes vote down vote up
private void fleeBullets(double tpf) {

        // from nature of code
        float desiredDistance = 50*3;

        Vec2 sum = new Vec2();
        count = 0;

        // check if it's too close
        bullets.forEach(bullet -> {

            double d = bullet.distance(runner);

            // If the distance is greater than 0 and less than an arbitrary amount (0 when you are yourself)
            if ((d > 0) && (d < desiredDistance)) {
                // Calculate vector pointing away from bullet
                Point2D diff = runner.getCenter().subtract(bullet.getCenter()).normalize().multiply(1 / d);

                sum.addLocal(diff.getX(), diff.getY());

                count++;
            }

            // TODO: java API ...
            return Unit.INSTANCE;
        });

        // we have a bullet close
        if (count > 0) {
            runner.getComponent(RandomMoveComponent.class).pause();

            // Our desired vector is moving away
            sum.normalizeLocal().mulLocal(moveSpeed * tpf * 1.5);

            runner.translate(sum);
        } else {
            runner.getComponent(RandomMoveComponent.class).resume();
        }
    }
 
Example #30
Source File: TagBoard.java    From OpenLabeler with Apache License 2.0 5 votes vote down vote up
private void onMouseClicked(MouseEvent me) {
   if (!me.getButton().equals(MouseButton.PRIMARY)) {
      me.consume();
      return;
   }
   if (Settings.getEditShape() == POLYGON) {
      Point2D pt = imageView.parentToLocal(me.getX(), me.getY());
      if (path == null) {
         // Start a polygon shape with double-click or SHORTCUT + mouse click
         if (!me.isShortcutDown() && me.getClickCount() != 2) {
            me.consume();
            return;
         }
         beginShape(pt);
      }
      else {
         // End a polygon shape with double-click (and space key)
         if (me.getClickCount() == 2) {
            endShape(pt);
            return;
         }
         path.getElements().add(new LineTo(pt.getX(), pt.getY()));
         points.add(pt);
         updatePath(pt);
      }
   }
   me.consume();
}