我正在使用JavaFX2上的拖放操作。拖拉对象(可能是被拖动对象的克隆)可能跟在鼠标光标之后,就像在JavaFX场景生成器上一样。
这是我的示例源代码:
Pane pane;
private void dragAndDropExample() {
pane = new Pane();
pane.setPrefSize(800, 600);
TitledPane titlePane = new TitledPane("Partial Order", pane);
add(titlePane, 0, 2);
pane.getChildren().add(createCircle(350, 300, Color.RED));
pane.getChildren().add(createCircle(250, 300, Color.BROWN));
pane.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (circleToMove != null) {
circleToMove.setCenterX(event.getX());
circleToMove.setCenterY(event.getY());
}
}
});
}
Circle circleToMove;
private Circle createCircle(double x, double y, Color color) {
final Circle c = new Circle(x, y, 25);
c.setFill(color);
c.setOnDragDetected(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent arg0) {
System.out.println("SetOnDragDetected");
c.setFill(Paint.valueOf("blue"));
Dragboard db = c.startDragAndDrop(TransferMode.COPY_OR_MOVE);
ClipboardContent content = new ClipboardContent();
content.putString("foo " + c.hashCode());
db.setContent(content);
arg0.consume();
circleToMove = c;
}
});
c.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println("Mouse clicked");
}
});
c.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println("Mouse Released");
circleToMove = null;
}
});
c.setOnDragExited(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
System.out.println("SetOnDragExited");
System.out.println(event.getGestureSource());
}
});
c.setOnDragOver(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
System.out.println("setOnDragOver " + c.hashCode());
c.setFill(Paint.valueOf("white"));
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
event.consume();
}
});
c.setOnDragDropped(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent arg0) {
System.out.println("setOnDragDropped");
c.setFill(Paint.valueOf("black"));
if (arg0.getGestureSource() instanceof Circle) {
if (arg0.getDragboard().hasString()) {
System.out.println(c.hashCode() + " hat jetzt " + arg0.getDragboard().getString());
}
}
}
});
c.setOnDragEntered(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent arg0) {
System.out.println("setOnDragEntered");
}
});
return c;
}
我尝试在窗格上使用mouseEvent,但在拖放过程中不会触发此事件。
答案 0 :(得分:4)
您使用的是错误的处理程序。拖动事件用于在窗格之间拖动项目。如果您只想移动被处理对象,请使用下一个代码:
private Circle createCircle(double x, double y, Color color) {
final Circle c = new Circle(x, y, 25);
c.setFill(color);
c.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
c.relocate(event.getSceneX() - c.getRadius(), event.getSceneY() - c.getRadius());
}
});
return c;
}
您也可以尝试查看Ensemble demo:
中的下一个子样本