Skip to content

Instantly share code, notes, and snippets.

@aoetk
Created April 17, 2012 04:13
Show Gist options
  • Save aoetk/2403405 to your computer and use it in GitHub Desktop.
Save aoetk/2403405 to your computer and use it in GitHub Desktop.
JavaFXでのDnDの例
package imageviewer;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
/**
* JavaFX でのDnDの例。
* 画像ファイルをドロップすると表示する。
*/
public class ImageViewer extends Application {
private int currentIndex = -1;
private List<String> imageFiles = new ArrayList<String>();
private ImageView currentImageView;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Image Viewer");
final Group root = new Group();
final Scene scene = new Scene(root, 550, 400, Color.BLACK);
currentImageView = new ImageView();
currentImageView.setPreserveRatio(true);
currentImageView.fitWidthProperty().bind(scene.widthProperty());
final HBox pictureRegion = new HBox();
pictureRegion.getChildren().add(currentImageView);
root.getChildren().add(pictureRegion);
scene.setOnDragOver(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
if (db.hasFiles()) {
event.acceptTransferModes(TransferMode.COPY);
}
event.consume();
}
});
scene.setOnDragDropped(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasFiles()) {
success = true;
String filePath = null;
for (File file : db.getFiles()) {
filePath = file.getAbsolutePath();
currentIndex++;
imageFiles.add(currentIndex, filePath);
System.out.println("file: " + filePath);
System.out.println("current index: " + currentIndex);
}
Image currentImage = new Image(filePath);
currentImageView.setImage(currentImage);
}
event.setDropCompleted(success);
event.consume();
}
});
primaryStage.setScene(scene);
primaryStage.show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment