我使用 SceneBuilder、3 个按钮和 2 个 ImageView 创建了一个小型 FXML 文件。
我想做的是:
- 运行应用并在启动时显示 2 张图像
- 按
NEXT
按钮时,显示另外2张图像。
我的问题不是切换图像,而是将图像显示为场景生成器创建的 ImageView。
这是我的 Controller 类:
public class Controller {
private Button Next; //1st button
private Button J2inc; //2nd button
private Button J1inc; /3rd button
private ImageView Img1;
private ImageView Img2;
void Inc2(ActionEvent event) {
//nothing for the moment
}
void Inc1(ActionEvent event) {
//nothing for the moment
}
void Nextimg(ActionEvent event) {
//nothing for the moment
}
}
还有我的start
方法:
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Css.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.setTitle("P ");
primaryStage.show();
}
我不知道如何初始化 ImageView img1
所以它会加载一些东西。
无法在此处添加 FXML,因此我只添加 ImageView 行:
<ImageView fx:id="Img1" fitHeight="750.0" fitWidth="450.0" layoutY="22.0" pickOnBounds="true" preserveRatio="true" AnchorPane.bottomAnchor="50.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="450.0" AnchorPane.topAnchor="25.0" />
最佳答案
要在 Controller 中初始化它,请通过注释 @FXML
使其可访问,并在 Controller 的 initialize()
方法中初始化它:
public class Controller {
private Button Next; //1st button
private Button J2inc; //2nd button
private Button J1inc; /3rd button
@FXML
private ImageView Img1;
private ImageView Img2;
public void initialize() {
Img1.setImage(new Image(...));
}
void Inc2(ActionEvent event) {
//nothing for the moment
}
void Inc1(ActionEvent event) {
//nothing for the moment
}
void Nextimg(ActionEvent event) {
//nothing for the moment
}
}
如果您希望直接在 FXML 中对其进行初始化,请为 image
属性提供一个值。在场景生成器中,您可以选择 ImageView
并在右上角的“图像”字段(“属性”下)中输入图像的 URL。请务必阅读Image
documentation了解如何解释 URL 的字符串表示形式。
关于java - 使用 SceneBuilder 显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42558641/