I am working on an app which needs to move nodes around on a pane.
I've just recently started learning javaFx 8 so I have bare understanding of the workflow, but while I managed to get a working draggable node code working, it uses node.setTranslateX() and .setTranslateY().
This is all fine, until I tried to make the node snap to a grid that divides the scene area in both 10 height and width subdivisions.
Whenever I try to use modulos to get some sort of snapping going on, I'm stuck with the fact that I'm calling Translation transformation. I'd like to directly set the coordinates of the node myself. I've tried node.relocate(x,y) to no avail. As for node.setX() or node.setY(). These do no seem to do much.
So basically, I have two questions:
- Is there a way to directly set the coordinates of a node ? If yes, how ?
- What is the correct way to snap a node to a grid while dragging it with the mouse ?
My current code uses these methods to drag the node around:
public class Boat extends ImageView {
private int size ;
private String name ;
private Double dragDeltaX, dragDeltaY;
//Constructor etc here//
this.setOnMousePressed(event -> {
this.setCursor(Cursor.CLOSED_HAND);
dragDeltaX = this.getLayoutX() + event.getX();
dragDeltaY = this.getLayoutY() + event.getY();
});
this.setOnMouseReleased(event -> {
this.setCursor(Cursor.OPEN_HAND);
this.relocate(event.getSceneX(), event.getSceneY());
});
this.setOnMouseDragged(event -> {
this.setTranslateX(event.getSceneX() - dragDeltaX);
this.setTranslateY(event.getSceneY() - dragDeltaY);
});
this.setOnMouseEntered(event -> {
this.setCursor(Cursor.OPEN_HAND);
});
}
Thanks in advance for the help,
In most
Pane
subclasses, if aNode
ismanaged
, then the parent pane of the node will manage itslayoutX
andlayoutY
properties. So settinglayoutX
andlayoutY
for these nodes will have no visible effect on the position of the node.Transformations (including the translation defined by
translateX
andtranslateY
) are applied to nodes after the layout calculations (whether the node is managed by its parent or not).So one way to manage dragging is just to manipulate the
translateX
andtranslateY
properties. Another way is to manipulate thelayoutX
andlayoutY
properties (by setting them directly or by callingrelocate
), and make sure the node is not managed by its parent. I would not recommend mixing the two techniques, as your code will be harder to follow.You can make the node unmanaged
setManaged(false)
on the node, or by putting it in aPane
instead of one of the subclasses (Pane
does not manage layout of its child nodes).