package testdnd;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class DndTest extends Application {
final static Image CONTENT_IMAGE = new Image(DndTest.class.getResource("JavaFX.png").toExternalForm());
final static String CONTENT_HTML =
""
+ ""
+ "
"
+ "Hello!"
+ "";
@Override
public void start(Stage stage) {
//Set up source
final Button source = new Button("Source");
source.setOnDragDetected(new EventHandler() {
@Override
public void handle(MouseEvent t) {
Dragboard db = source.startDragAndDrop(TransferMode.COPY);
ClipboardContent content = new ClipboardContent();
content.putImage(CONTENT_IMAGE);
content.putHtml(CONTENT_HTML);
db.setContent(content);
t.consume();
}
});
source.setOnDragDone(new EventHandler() {
@Override
public void handle(DragEvent t) {
System.out.println("Drag done");
}
});
final Button target = new Button("Destination");
target.setOnDragOver(new EventHandler() {
@Override
public void handle(DragEvent t) {
if (t.getGestureSource() != target)
{
t.acceptTransferModes(TransferMode.ANY);
}
t.consume();
}
});
target.setOnDragDropped(new EventHandler() {
@Override
public void handle(DragEvent t) {
System.out.println("On drag dropped");
boolean result = false;
if (t.getGestureSource() == target) {
return;
}
Clipboard cb = t.getDragboard();
if (cb.hasHtml()) {
System.out.println("Dropped HTML: " + cb.getHtml());
result = true;
}
if (cb.hasImage()) {
System.out.println("Dropped image: " + cb.getImage());
result = true;
}
t.setDropCompleted(result);
t.consume();
}
});
HBox root = new HBox(10d);
root.getChildren().addAll(source, target);
Scene scene = new Scene(root, 300, 250);
stage.setScene(scene);
stage.setTitle(System.getProperty("java.runtime.version") + "; " + System.getProperty("javafx.runtime.version"));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}