在 JavaFX 和 Scenebuilder 中创建新的 ImageViews



我要再试一次...我是Scenebuilder的新手,我正在尝试为我的项目制作一个照片库!我已经添加了我想要的东西,即一个图像视图,其中包含从文件选择器中选择的图像......但是现在我想得到一个建议,如何保存这个并在每次按下addPhoto按钮时创建一个新的按钮,而不是覆盖我在ImageView中已有的那个。这是我的AddPhoto按钮的代码:

@FXML
public void initialize(ActionEvent e) throws Exception{

addPhotos.setOnAction(event -> {
FileChooser chooser = new FileChooser();
File file = chooser.showOpenDialog(null);
pic = new Image(file.toURI().toString());
if(pic != null) {
ImageView  imgView = new ImageView(pic);
}
imgView.setImage(pic);
});

FXML代码:

<BorderPane prefHeight="737.0" prefWidth="934.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="legioDesk.GalleryController">
<top>
<Button fx:id="addPhotos" mnemonicParsing="false" onAction="#initialize" text="addPhotos" BorderPane.alignment="CENTER" />
</top>
<center>
<TilePane fx:id="tp" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
<children>
<ImageView fx:id="imgView" fitHeight="306.0" fitWidth="378.0" pickOnBounds="true" preserveRatio="true" />
</children>
</TilePane>
</center>
</BorderPane>

您在事件处理程序中创建了一个新ImageView,但您从未对它执行任何操作,因此它只是被丢弃。

请注意,两个ImageView具有相同的变量名称:您创建(和丢弃(的变量名称的作用域为if块,因此您在块外部引用的变量是您在 FXML 文件中定义的变量名称。

所以你的代码可以

@FXML
public void initialize(ActionEvent e) throws Exception{

addPhotos.setOnAction(event -> {
FileChooser chooser = new FileChooser();
File file = chooser.showOpenDialog(null);
pic = new Image(file.toURI().toString());
if(pic != null) {
// Create a new image view, containing the selected image
// (but do nothing with it)
ImageView  imgView = new ImageView(pic);
}
// now update the existing ImageView (from the FXML file) with
// the chosen image:
imgView.setImage(pic);
});
}

您要做的(我猜,因为您没有非常清楚地解释所需的行为(是将新的图像视图添加到磁贴窗格:

@FXML
public void initialize(ActionEvent e) throws Exception{

addPhotos.setOnAction(event -> {
FileChooser chooser = new FileChooser();
File file = chooser.showOpenDialog(null);
pic = new Image(file.toURI().toString());
if(pic != null) {
ImageView  imgView = new ImageView(pic);
imgView.setFitWidth(306);
imgView.setFitHeight(378);
imgView.setPreserveRatio(true);
tp.getChildren().add(imgView);
}
});
}

当然,您不需要FXML文件中的图像视图:

<BorderPane prefHeight="737.0" prefWidth="934.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="legioDesk.GalleryController">
<top>
<Button fx:id="addPhotos" mnemonicParsing="false" onAction="#initialize" text="addPhotos" BorderPane.alignment="CENTER" />
</top>
<center>
<TilePane fx:id="tp" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
</TilePane>
</center>
</BorderPane>

好的,因为您说单个图像版本有效,现在您想添加一个新图像。获取您的 TilePane,获取子级,然后添加您的图像视图。

pic = new Image(file.toURI().toString());
if(pic != null) {
ImageView  nextView = new ImageView(pic);
tp.getChildren().add(nextView);
}
//delete this it is changing the original one.
//imgView.setImage(pic);

这可能有效,但我无法测试它,因为您没有提供足够的代码。

最新更新