具有变量url的fxml文件上的JavaFx Image

问题描述 投票:0回答:1

我试图在谷歌上找到我的答案,但现在没有结果。

所以如果它已经解决了,我很抱歉。

我想做的事情:当我的FXML文件加载时,我希望此文件中的imageView从URL中加载图像,该URL包含在包含不同URL的字符串表中,因此我可以根据加载时切换图像。我的choice变量。我尝试过绝对路径和相对路径。

在我的主要:

//url tab of the 2 images
public static String[] images = new String[2];

//variable that include the choice for the image to load in the tab images
public static int choice = 0;

public MainTest() {
    images[0] = "C:/Users/Stagiaire ACI/Desktop/Java/ImageTestImage/Assasin.png";
    images[1] = "C:/Users/Stagiaire ACI/Desktop/Java/ImageTestImage/Barde.png";
}

我的fxml文件控制器:

@FXML
private ImageView image;

@FXML
private void initialize() {
    Image image = new Image(MainTest.images[MainTest.choice]);
    this.image.setImage(image);
}

和我的Fxml文件:

<AnchorPane prefHeight="600.0" prefWidth="900.0" xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.test.view.TestControler">
   <children>
      <ImageView fx:id="image" fitHeight="310.0" fitWidth="319.0" layoutX="306.0" layoutY="183.0" pickOnBounds="true" preserveRatio="true" />
   </children>
</AnchorPane>

所以有了这个,我可以改变choice来改变负载上的图像。当我用经典方式加载它时,我的图像效果很好。

甚至不知道是否可能。

谢谢!

编辑:我已经通过将file:放在文件URL上方解决了我的问题。

eclipse javafx fxml scenebuilder
1个回答
1
投票

@对具有以FXMLLoader开头的值的URL属性进行了不同的处理。它们被视为相对于文档。这在fxmls之外不起作用。

绝对文件路径不起作用,因为它们不包含协议。

如果您的图像是资源,您应该使用Class.getResource,如果不是,请使用File.toURI().toURL()

images[0] = MainTest.class.getResource("/absolute/package/path/Assasin.png").toExternalForm();
images[1] = new File("C:/Users/Stagiaire ACI/Desktop/Java/ImageTestImage/Barde.png").toURI().toURL().toExternalForm();
© www.soinside.com 2019 - 2024. All rights reserved.