Skip to content

Instantly share code, notes, and snippets.

@am4dr
Created January 21, 2017 19:00
Show Gist options
  • Save am4dr/b5f5a03569affd3099820afcf5768fa1 to your computer and use it in GitHub Desktop.
Save am4dr/b5f5a03569affd3099820afcf5768fa1 to your computer and use it in GitHub Desktop.
JavaFX でアプリケーション外からのドラッグ・ドロップを処理する例。
/*
JavaFX でアプリケーション外からのドラッグ・ドロップを処理する。
Nodeに対してD&Dを受けつけるという設定を行うことでFileのリストを得られる。
参考:
[Node (JavaFX 8)](http://docs.oracle.com/javase/jp/8/javafx/api/javafx/scene/Node.html#onDragDroppedProperty)
[DragEvent (JavaFX 8)](http://docs.oracle.com/javase/jp/8/javafx/api/javafx/scene/input/DragEvent.html)
[Clipboard (JavaFX 8)](http://docs.oracle.com/javase/jp/8/javafx/api/javafx/scene/input/Clipboard.html)
*/
import javafx.application.Application
import javafx.event.EventHandler
import javafx.scene.Scene
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.input.DataFormat
import javafx.scene.input.TransferMode
import javafx.scene.layout.Pane
import javafx.stage.Stage
class App extends Application {
void start(Stage stage) {
def iv = new ImageView()
def p = new Pane(iv)
//p.children.add(iv)
p.onDragOverProperty().set({ e ->
// このNode上にDropできるかどうかのヒントをシステムに与える
// Windowsだと「コピー」や「送る」というツールチップが
// ドラッグ中のカーソルの横に表示されるようになる
e.acceptTransferModes(TransferMode.COPY_OR_MOVE)
e.consume()
} as EventHandler)
p.onDragDroppedProperty().set({ e ->
def db = e.dragboard
iv.image = db.image
println "Dropped: $e, $db"
println "contentTypes: ${db.contentTypes}"
println "files: ${db.files}"
println "html: ${db.html}"
println "image: ${db.image}"
println "rtf: ${db.rtf}"
println "string: ${db.string}"
println "text: ${db.getContent(DataFormat.PLAIN_TEXT)}"
println "url: ${db.getContent(DataFormat.URL)}"
if (db.hasFiles()) {
def url = db.files[0].toURI().toURL()
println "url: $url"
def image = new Image(url.toString())
iv.image = image
}
e.dropCompleted = true // ドロップが成功したかどうか
e.consume()
} as EventHandler)
stage.scene = new Scene(p, 600, 400)
stage.show()
}
}
Application.launch(App)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment