简体   繁体   English

在JAVA FX中加载图像

[英]Load Image in JAVA FX

im trying to load image from file system, but i have no error and don't display image. 即时通讯试图从文件系统加载图像,但我没有错误,也不显示图像。 THe file of the image is in the Package folder ../src/application/a.png , i try to load image in different way like this: 图像文件位于Package文件夹../src/application/a.png中,我尝试以不同方式加载图像,如下所示:

Image image = new Image("file:a.png"); 图片image = new Image(“ file:a.png”);

Image image = new Image(new File("a.png").toURI().toString()); 图片image = new Image(new File(“ a.png”)。toURI()。toString());

package application;

import java.io.File;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage stage) {

        Image image = new Image(new File("/a.png").toURI().toString());
        // Setting the image view
        ImageView imageView = new ImageView(image);
        // Setting the position of the image
        imageView.setX(0);
        imageView.setY(0);
        // setting the fit height and width of the image view
        imageView.setFitHeight(200);
        imageView.setFitWidth(400);
        // Setting the preserve ratio of the image view
        imageView.setPreserveRatio(true);



        // Creating a Group object
        Group root = new Group(imageView);

        // Creating a scene object
        Scene scene = new Scene(root, 600, 300);
        // Setting title to the Stage
        stage.setTitle("Coloradjust effect example");
        // Adding scene to the stage
        stage.setScene(scene);

        // Displaying the contents of the stage
        stage.show();
    }

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

thanks for help 感谢帮助

If the image you are trying to load is in the same directory as your class, try: 如果您要加载的图像与您的类位于同一目录中,请尝试:

image = new Image(getClass().getResourceAsStream("a.png")). image = new Image(getClass()。getResourceAsStream(“ a.png”))。

Else, if it is in a sub-directory of the directory your class belongs to, try: 否则,如果它位于您的课程所属目录的子目录中,请尝试:

image = new Image(getClass().getResourceAsStream("application/a.png")). 图片=新图片(getClass()。getResourceAsStream(“ application / a.png”))。 Given that your project structure is: 鉴于您的项目结构为:

|----src | ---- src

|----Main | ----主要

|--------application | --------申请

|--------a.png | -------- a.png

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM