Created
April 17, 2012 04:13
-
-
Save aoetk/2403405 to your computer and use it in GitHub Desktop.
JavaFXでのDnDの例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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