我是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中尝试了一下--它的工作方式是正常的
项目结构
附注:我可以使用getClass().getClassLoader().getResource()
设置图像,但画布大小仍然大于它设置的大小。路径与SceneBuilder中使用的路径相同
发布于 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
https://stackoverflow.com/questions/51574812
复制相似问题