1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| public class Main extends Application {
public final static DataFormat DND_SOURCE_FORMAT = new DataFormat("dnd-source");
@Override
public void start(Stage primaryStage) {
final Pane source1 = new Pane();
source1.setId("source1");
source1.setStyle("-fx-background-color: red; -fx-border-color: red;");
source1.setOnDragDetected(mouseEvent -> startDnD(mouseEvent, source1));
HBox.setHgrow(source1, Priority.ALWAYS);
final Pane source2 = new Pane();
source2.setId("source2");
source2.setStyle("-fx-background-color: blue; -fx-border-color: blue;");
source2.setOnDragDetected(mouseEvent -> startDnD(mouseEvent, source2));
HBox.setHgrow(source2, Priority.ALWAYS);
final Pane target = new Pane();
target.setId("target");
target.setStyle("-fx-background-color: green; -fx-border-color: green;");
target.setOnDragOver(dragEvent -> handleDragOver(dragEvent, target));
target.setOnDragDropped(dragEvent -> handleDragDropped(dragEvent, target));
VBox.setVgrow(target, Priority.ALWAYS);
final HBox source = new HBox(source1, source2);
source.setFillHeight(true);
VBox.setVgrow(source, Priority.ALWAYS);
final VBox root = new VBox(source, target);
root.setFillWidth(true);
final Scene scene = new Scene(root, 500, 500);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
private void startDnD(MouseEvent mouseEvent, Node source) {
final Dragboard dragboard = source.startDragAndDrop(TransferMode.ANY);
final ClipboardContent content = new ClipboardContent();
content.put(DND_SOURCE_FORMAT, source.getId());
dragboard.setContent(content);
mouseEvent.consume();
}
private void handleDragOver(DragEvent dragEvent, Node target) {
final Dragboard dragboard = dragEvent.getDragboard();
if (dragEvent.getGestureSource() != target && dragboard.hasContent(DND_SOURCE_FORMAT)) {
dragEvent.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
dragEvent.consume();
}
private void handleDragDropped(DragEvent dragEvent, Node target) {
final Dragboard dragboard = dragEvent.getDragboard();
boolean success = false;
if (dragboard.hasContent(DND_SOURCE_FORMAT)) {
System.out.println(dragboard.getContent(DND_SOURCE_FORMAT));
System.out.println(dragEvent.getGestureSource());
success = true;
}
dragEvent.setDropCompleted(success);
dragEvent.consume();
}
public static void main(String[] args) {
launch(args);
}
} |
Partager