所以,我是JavaFX的新手,作为项目的一部分,我试图使用ImageView来显示一些图像 . 在添加到我的实际项目之前,我设置了以下内容以确保我了解如何使用ImageViews .
我的控制器:
import javafx.fxml.FXML;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
public class TestController {
@FXML
ImageView imageView;
Image image;
public void start(Stage stage){
/*
* THIS WORKS!
*
* image = new Image("file:/C://Users//Owner//Pictures//MyProjectPhotos/picture.jpg");
*/
//BUT THIS DOESN'T :(
image = new Image("file:/JavaFXPractice/photos/picture.jpg");
imageView.setImage(image);
imageView.setOnMouseClicked(me -> System.out.println("hello"));
}
}
fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.VBox?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"
minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0"
xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="application.TestController">
<children>
<VBox layoutX="156.0" layoutY="88.0" prefHeight="272.0" prefWidth="378.0">
<children>
<ImageView fx:id="imageView" fitHeight="276.0" fitWidth="378.0"
pickOnBounds="true" preserveRatio="true" />
</children>
</VBox>
</children>
</AnchorPane>
最后这个:
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/view/TestPage.fxml"));
AnchorPane root = (AnchorPane) loader.load();
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
TestController control = loader.getController();
control.start(primaryStage);
}
public static void main(String[] args) {
launch(args);
}
}
我的问题出在TestController类中 . 正如您在多行注释(以及它下面的注释/代码行)中看到的那样,当我从本地计算机上获取图像时,图像会正确显示,但是当我从项目空间获取图像时,图像不会显示 . 我已经尝试了几个小时来解决这个问题,但每次我尝试从项目空间中检索任何照片时,ImageView上都没有显示任何内容 . 它不是null(图像也不是),并且没有报告错误 . 我也试过寻找答案,但到目前为止还没有运气 .
1 回答
您可以像这样加载图片:
在假设下,“照片”是项目根目录下的文件夹 . 此文件夹必须位于类路径中 . 根据您的IDE,这可以通过不同的方式实现 . 在Eclipse中,可以通过将此文件夹放入“源文件夹”来实现 . 典型的结构是
其中“src”和“res”都是源文件夹 .