【问题标题】:Change ImageView image in code using JavaFX Scene Builder使用 JavaFX Scene Builder 在代码中更改 ImageView 图像
【发布时间】:2017-03-07 12:01:11
【问题描述】:

我正在尝试在单击按钮时更改 ImageView 组件中的图像。我需要它是本地图像。我不断收到路径错误,无法使用 ImageIcon 并将其转换为 Image。有没有一种简单的方法可以做到这一点?

package tictactoesimulator_alliebeckman;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

/**
 *
 * @author Allie
 */
public class FXMLDocumentController implements Initializable {

    // my components        
    @FXML
    public Label lblWinLose;
    @FXML
    public Button btnNewGame;
    @FXML
    public ImageView ivOne;

    // Event handle for button click  
    @FXML
    public void handleButtonAction(ActionEvent event) {

        // here is where I'm having the issue I have the image file in my src folder
        // I've tried using a ImageIcon and it wont convert to an Image?
        // All I need is the image to change to the local image on button click

        lblWinLose.setText("Clicked");
        Image image = new Image("o.png");
        ivOne = new ImageView(image);
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {

    }
}

项目布局可以在这个 Eclipse 截图中看到:

【问题讨论】:

  • 请您发布堆栈跟踪
  • java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found

标签: java image javafx imageview scenebuilder


【解决方案1】:

从您问题的屏幕截图中,该图像与FXMLDocumentController 类位于同一包中。

您正在使用的 Image constructor 期望图像的 URL 的字符串版本:获取此类 URL 的最佳方法是使用 getClass().getResource(...)(因为无论您正在从文件系统或 jar 文件加载)。 getClass().getResource(...) 将相对于当前类进行解析(如果资源名称以 / 开头,则相对于类路径):

Image image = new Image(getClass().getResource("o.png").toExternalForm());

然后你应该这样做而不是创建一个新的ImageView

ivOne.setImage(image);

【讨论】:

  • 如果文件 o.png 确实位于类路径的根目录中,new Image("o.png") 应该可以工作,因为您手动执行的操作已经在 Image 构造函数中完成了 thx to validateUrl
  • @NicolasFilotto 好点。可能需要更多关于实际情况的信息。
  • 非常感谢您帮助我。我尝试了这两个答案,但仍然无法正常工作,我想我的图片可能在错误的文件夹中?
  • @AllieMarie 啊,所以你的图像与类在同一个包中,而不是在类路径的根目录中。相应地更新了答案。
  • 成功了,谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
  • 1970-01-01
  • 2016-07-27
  • 2013-11-21
  • 1970-01-01
相关资源
最近更新 更多