有人可以举一个关于如何设置EventHandler以在Pane(JavaFX)上拖动图像视图的简单示例。对于拖动,我的意思是在图像上按鼠标,拖动图像,然后释放鼠标,图像视图将停在那个位置。
答案 0 :(得分:1)
首先阅读文档Drag and drop in javafx
或者您可以通过getMouseX
和getMouseY
点自行完成,并在AnchorPane
中更改imageView的坐标....
答案 1 :(得分:0)
我想通过拖放尝试提出的解决方案。我发现它不是最佳的。
通过拖放操作,您可以触发一些不必要的机制:
更少,如果有人感兴趣,这是我的代码:
Main.java
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
Controller controller = new Controller();
loader.setController(controller);
Parent root = (Parent)loader.load();
controller.InitUi();
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller.java
package sample;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.input.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.shape.Rectangle;
public class Controller
{
@FXML
private Rectangle draggable;
private Double lastX = null;
private Double lastY = null;
public void InitUi()
{
if (this.draggable != null)
{
this.draggable.setOnDragOver(new EventHandler<DragEvent>()
{
@Override
public void handle(DragEvent dragEvent)
{
HandleMouseMovement(dragEvent.getSceneX(), dragEvent.getSceneY());
}
});
this.draggable.setOnDragDetected(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
Dragboard db = draggable.startDragAndDrop(TransferMode.ANY);
ClipboardContent content = new ClipboardContent();
content.putString("Does not matter");
db.setContent(content);
event.consume();
lastX = event.getSceneX();
lastY = event.getSceneY();
}
});
}
}
private synchronized void HandleMouseMovement(double sceneX, double sceneY)
{
double deltaX = sceneX - lastX;
double deltaY = sceneY - lastY;
lastX = sceneX;
lastY = sceneY;
double currentXAnchor =AnchorPane.getLeftAnchor(this.draggable);
double currentYAnchor =AnchorPane.getTopAnchor(this.draggable);
AnchorPane.setLeftAnchor( this.draggable, currentXAnchor + deltaX*1.5);
AnchorPane.setTopAnchor(this.draggable, currentYAnchor + deltaY*1.5);
}
}
sample.fxml
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.shape.Rectangle?>
<GridPane xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10" prefHeight="500" prefWidth="500">
<AnchorPane>
<Rectangle fx:id="draggable" width="40" height="50" AnchorPane.topAnchor="20" AnchorPane.leftAnchor="20"/>
</AnchorPane>
</GridPane>