我几乎尝试了所有操作,但没有触发鼠标拖动事件,如此处所述:
https://openjfx.io/javadoc/11/javafx.graphics/javafx/scene/input/MouseDragEvent.html
这是一个最小的示例,因此您可以尝试一下(我将Java 11与JavaFX 11.0.2一起使用):
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Main extends Application {
private double mouseClickPositionX, mouseClickPositionY, currentRelativePositionX, currentRelativePositionY;
@Override
public void start(Stage primaryStage) throws Exception{
primaryStage.setTitle("Hello World");
BorderPane mainBorderPane = new BorderPane();
BorderPane centerBorderPane = new BorderPane();
FlowPane flowPane = new FlowPane();
GridPane gridPane = new GridPane();
Button button1 = new Button("button1");
gridPane.add(button1, 0, 0);
flowPane.getChildren().add(gridPane);
centerBorderPane.setCenter(flowPane);
HBox hbox = new HBox();
TilePane tilePane = new TilePane();
Button button2 = new Button("button2");
tilePane.getChildren().add(button2);
hbox.getChildren().add(tilePane);
mainBorderPane.setCenter(centerBorderPane);
centerBorderPane.setBottom(hbox);
// button2 event handlers
button2.setOnMousePressed(event -> {
mouseClickPositionX = event.getSceneX();
mouseClickPositionY = event.getSceneY();
currentRelativePositionX = button2.getTranslateX();
currentRelativePositionY = button2.getTranslateY();
button2.setMouseTransparent(true);
});
button2.setOnMouseDragged(event -> {
button2.setTranslateX(currentRelativePositionX + (event.getSceneX() - mouseClickPositionX));
button2.setTranslateY(currentRelativePositionY + (event.getSceneY() - mouseClickPositionY));
});
button2.setOnDragDetected(event -> {
button2.startFullDrag();
});
button2.setOnMouseReleased((event) -> {
button2.setMouseTransparent(false);
});
// button1 event handlers
button1.setOnMouseDragReleased((event) -> {
System.out.println("it works in button1");
});
// gridPane event handlers
gridPane.setOnMouseDragReleased((event) -> {
System.out.println("it works in gridPane");
});
primaryStage.setScene(new Scene(mainBorderPane, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
我想通过button2
在button1
或gridPane
中获得setOnMouseDragReleased
的引用。有很多嵌套的窗格等,因为我想保持原始的项目布局结构。我这样做是因为我不确定这是否也可能是无法正常运行的原因。
谢谢。
答案 0 :(得分:0)
MOUSE_DRAG_RELEASED在该节点上的拖动结束时触发。例如
centerBorderPane.setOnMouseDragReleased((event) -> {
System.out.println("centerBorderPane drag released");
});
当拖动button2
且拖动结束于centerBorderPane
时应触发。
要在鼠标悬停在button1
上时触发事件,请使用button1.setOnMouseDragged
如果要将鼠标事件从父事件传播到其子事件,请参见this
答案 1 :(得分:0)
我最终使用centerBorderPane
手动触发了从gridPane
到node.fireEvent(event)
的事件。还实现了一个辅助函数,该函数返回正确的子节点:
private Optional<Node> findNode(Pane pane, double x, double y) {
return pane.getChildren().stream().filter(n -> {
Point2D point = n.sceneToLocal(x, y);
return n.contains(point.getX(), point.getY());
}).findAny();
}
别忘了消耗事件,因此您不会陷入无限循环。