首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JavaFX | IntelliJ Idea| ImageView不显示SceneBuilder中显示的图像及其预览

JavaFX | IntelliJ Idea| ImageView不显示SceneBuilder中显示的图像及其预览
EN

Stack Overflow用户
提问于 2018-07-29 04:00:16
回答 1查看 3.1K关注 0票数 0

我是JavaFX的新手,所以我不明白哪里出了问题。我已经在SceneBuilder中向ImageView%s添加了图像。在SceneBuilder和它的预览中,我们可以看到它们。但是当我运行我的应用程序时,只显示空窗口(视觉上,画布大小不同)

Main.java:

package application;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("MainMenu.fxml"));
        primaryStage.setTitle("MainMenu");
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

MainMenu.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="720.0" prefWidth="1280.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MainMenuController">
    <children>
        <ImageView fx:id="background" fitHeight="720.0" fitWidth="1280.0" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="@../../assets/mainMenuScreen/background.png" />
         </image></ImageView>
    </children>
</AnchorPane>

我在Eclipse中尝试了一下--它的工作方式是正常的

项目结构

SceneBuilder View

Running View

附注:我可以使用getClass().getClassLoader().getResource()设置图像,但画布大小仍然大于它设置的大小。路径与SceneBuilder中使用的路径相同

EN

回答 1

Stack Overflow用户

发布于 2018-07-29 04:36:52

这是因为path。我不知道如何在fxml中做到这一点(我试过)。从代码开始就可以了

1)初始化你的ImageView的fx:id,比如fx:id="imView"

2)在代码中初始化并设置image。(在src中创建文件夹'resources‘)

@FXML
private ImageView imView;

@FXML
public void initialize(){
    imView.setImage(
            new Image("resources/yourImage.jpg")
    );
}

如果您还希望您的图像始终适合窗口大小,则应该向其添加侦听器:

假设您的ImageView位于AnchorPane内部

@FXML
private AnchorPane root;

@FXML
private ImageView imView;

@FXML
public void initialize(){
    imView.setImage(
            new Image("ims/Weissmanscore.jpg")
    );
    root.heightProperty().addListener(
            h -> imView.setFitHeight(
                    root.getHeight()
            )
    );
    root.widthProperty().addListener(
            h -> imView.setFitWidth(
                    root.getWidth()
            )
    );
}

如果你不想你的图片保持比例和调整窗口的轴向大小,只需在代码imView.setPreserveRatio(false);的FXML preserveRatio="true"中将preserveRatio设置为false

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51574812

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档