我尝试一次编辑文件夹中的五张图片(使用javafx运动模糊),而不是一个接一个地选择它们。这是我的代码,我不确定我做错了什么,但是当我运行它时,只有文件夹中的最后一个图像被编辑。其他人保持不变。
public class IterateThrough extends Application {
private Desktop desktop = Desktop.getDesktop();
@Override
public void start(Stage primaryStage) throws IOException {
File dir = new File("filepath");
File [] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File file : directoryListing) {
if(file.getName().toLowerCase().endsWith(".jpeg")){
//desktop.open(file);
Image image = new Image(new FileInputStream(file));
//Setting the image view
ImageView imageView = new ImageView(image);
//setting the fit height and width of the image view
imageView.setFitHeight(600);
imageView.setFitWidth(500);
//Setting the preserve ratio of the image view
imageView.setPreserveRatio(true);
// instantiate Motion Blur class
MotionBlur motionBlur = new MotionBlur();
// set blur radius and blur angle
motionBlur.setRadius(15.0);
motionBlur.setAngle(110.0);
//set imageView effect
imageView.setEffect(motionBlur);
//Creating a Group object
Group root = new Group(imageView);
//Creating a scene object
Scene scene = new Scene(root, 600, 500);
//Setting title to the Stage
primaryStage.setTitle("Loading an image");
//Adding scene to the stage
primaryStage.setScene(scene);
//Displaying the contents of the stage
primaryStage.show();
}
}
}
}
public static void main(String[] args) {
launch(args);
}
}
答案 0 :(得分:0)
首先,你不应该让forStress show()在for-each循环中,因为当primaryStage第一次show()时,fx线程在该指令上暂停,剩下的图片将不被读取,当你关闭窗口时,循环不会继续继续,它代表应用程序的结束。
所以最好在读取完所有图像后让primaryStage show()在每个循环之外。
第二,你不应该使用" Group"容器包含所有图像,更好地使用VBox / HBox / FlowPane,确保上面的图像不会覆盖下面的。
此处修改后的代码供参考。
public class IterateThrough2 extends Application{
private Desktop desktop = Desktop.getDesktop();
@Override
public void start(Stage primaryStage) throws IOException{
File dir = new File("filepath");
File[] directoryListing = dir.listFiles();
FlowPane root = new FlowPane();
if(directoryListing != null){
for(File file : directoryListing){
if(file.getName().toLowerCase().endsWith(".jpeg")){
Image image = new Image(new FileInputStream(file));
ImageView imageView = new ImageView(image);
imageView.setFitHeight(600);
imageView.setFitWidth(500);
imageView.setPreserveRatio(true);
MotionBlur motionBlur = new MotionBlur();
motionBlur.setRadius(15.0);
motionBlur.setAngle(110.0);
imageView.setEffect(motionBlur);
root.getChildren().add(imageView);
}
}
}
Scene scene = new Scene(root, 600, 500);
primaryStage.setTitle("Loading an image");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args){
launch(args);
}
}