场景:我想在JFXPanel内向水平方向拖动(拖动山墙节点),即标签(标签系列),它应该垂直固定....
我指的是Link .....但我无法限制用户垂直拖动,所以有人帮我....标签应该只是垂直拖动水平。
答案 0 :(得分:1)
这是一个例子。我注释掉了Y平移,因此您只能水平拖动标签。
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
public class DragNodesHorizontally extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Group root = new Group();
// create label
Label label = new Label( "Drag me");
label.relocate(100,100);
// make label draggable
MouseGestures mg = new MouseGestures();
mg.makeDraggable( label);
root.getChildren().addAll( label);
primaryStage.setScene(new Scene(root, 1024, 768));
primaryStage.show();
}
public static class MouseGestures {
class DragContext {
double x;
double y;
}
DragContext dragContext = new DragContext();
public void makeDraggable( Node node) {
node.setOnMousePressed( onMousePressedEventHandler);
node.setOnMouseDragged( onMouseDraggedEventHandler);
}
EventHandler<MouseEvent> onMousePressedEventHandler = event -> {
Node node = ((Node) (event.getSource()));
dragContext.x = node.getTranslateX() - event.getSceneX();
dragContext.y = node.getTranslateY() - event.getSceneY();
};
EventHandler<MouseEvent> onMouseDraggedEventHandler = event -> {
Node node = ((Node) (event.getSource()));
node.setTranslateX( dragContext.x + event.getSceneX());
// node.setTranslateY( dragContext.y + event.getSceneY()); // uncomment this if you want x/y dragging
};
}
}
在您发布的链接中,您也可以将offsetY设置为0。