[英]Change ImageView image in code using JavaFX Scene Builder
我正在尝试在按钮单击时更改ImageView组件中的图像。 我需要它是一个本地图像。 我一直收到路径错误,我不能使用ImageIcon并将其转换为图像。 有没有一个简单的方法来做到这一点?
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屏幕截图中看到项目布局:
从您问题中的屏幕截图中,该图像与FXMLDocumentController
类位于同一个包中。
您正在使用的Image
构造函数期望图像的URL的字符串版本 :获取此类URL的最佳方法是使用getClass().getResource(...)
(因为无论您是从文件系统或从jar文件)。 getClass().getResource(...)
将相对于当前类(或相对于类路径,如果您使用前导/
开始资源名称getClass().getResource(...)
解析:
Image image = new Image(getClass().getResource("o.png").toExternalForm());
然后你应该做的不是创建一个新的ImageView
ivOne.setImage(image);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.