Java Reference
In-Depth Information
The following code fragment sets the openButton 's icon from the CSS style sheet.
#openButton {
-fx-graphic: url("resources/music_note.png");
}
The next step is to add the drag-and-drop support. The drag event handlers are added to the Scene
because we want to support the dropping of a file or URL anywhere on the application. Listing 9-13 shows the
initSceneDragAndDrop method that creates these event handlers.
Listing 9-13. The DragEvent Handlers for the Scene
private void initSceneDragAndDrop(Scene scene) {
scene.setOnDragOver(event -> {
Dragboard db = event.getDragboard();
if (db.hasFiles() || db.hasUrl()) {
event.acceptTransferModes(TransferMode.ANY);
}
event.consume();
});
scene.setOnDragDropped(event -> {
Dragboard db = event.getDragboard();
String url = null;
if (db.hasFiles()) {
url = db.getFiles().get(0).toURI().toString();
} else if (db.hasUrl()) {
url = db.getUrl();
}
if (url != null) {
songModel.setURL(url);
songModel.getMediaPlayer().play();
}
event.setDropCompleted(url != null);
event.consume();
});
}
The handler for the DRAG_OVER event checks to make sure that this drag contains either files or a URL. If so, it
calls DragEvent 's acceptTransferModes method to set which types of TransferMode s are supported. In this case we
indicate that any type of transfer is supported. Other options are COPY , LINK , and MOVE . Because we are interested only
in the string form of the file's URL or in an actual URL string, we can accept any type of transfer. It is important to call
the acceptTransferModes method in your DRAG_OVER handler because on many platforms that will affect the visual
feedback the user receives as he or she moves her drag cursor over your window.
The DRAG_DROPPED handler gets the URL of the first file in the list of dropped files or the URL itself if that is what is
being dragged. Just as with the file chooser code, it then passes this URL to the SongModel and begins playback of the
song. The final step in the drag operation is to call the setDropCompleted method of the DragEvent to inform it that
the drop was successfully completed.
 
Search WWH ::




Custom Search