【问题标题】:Keep getting error in JavaFX every time I try to add an image. java.lang.reflect.InvocationTargetException每次我尝试添加图像时,JavaFX 中都会出现错误。 java.lang.reflect.InvocationTargetException
【发布时间】:2019-12-03 05:25:33
【问题描述】:

在过去的几天里,我想尽一切办法在 JavaFx 上获取图像。而且无论我尝试什么,它总是相同的错误。无论我做什么,它总是同样的错误。此错误仅发生在图像上。当我使用 try-catch 时,我打印出的异常是 java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found.

 package application;

 import java.io.FileInputStream;
 import java.io.FileNotFoundException;

 import javafx.application.Application;
 import javafx.geometry.Pos;
 import javafx.scene.Group;
 import javafx.scene.Scene;
 import javafx.scene.control.Label;
 import javafx.scene.image.Image;
 import javafx.scene.image.ImageView;
 import javafx.scene.layout.GridPane;
 import javafx.scene.paint.Color;
 import javafx.scene.text.Font;
 import javafx.scene.text.FontWeight;
 import javafx.stage.Stage;

public class Practice extends Application {
     public void start(Stage stage) throws FileNotFoundException {         
      //Creating an image 
      Image image = new Image(new 
FileInputStream("Users/user/Documents/Minesweeper/1.png"));  

      //Setting the image view 
      ImageView imageView = new ImageView(image); 

      //Setting the position of the image 
      imageView.setX(50); 
      imageView.setY(25); 

      //setting the fit height and width of the image view 
      imageView.setFitHeight(455); 
      imageView.setFitWidth(500); 

      //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, 500);  

      //Setting title to the Stage 
      stage.setTitle("Loading an image");  

      //Adding scene to the stage 
      stage.setScene(scene);

      //Displaying the contents of the stage 
      stage.show(); 
   }  
   public static void main(String args[]) { 
      launch(args); 
   } 

}

【问题讨论】:

    标签: java


    【解决方案1】:

    检查图像文件的路径。路径"Users/user/Documents/Minesweeper/1.png"是相对路径,确保Users上面的目录是你当前的工作目录。

    否则,您可以将图像的绝对路径作为FileInputStream 的参数。

    简单的java文件结构应该是这样的:

    工作目录 | - - 应用 | | | ----实践.java |----1.png

    使用此结构,您将能够将图像加载为

    Image image = new Image(new FileInputStream("1.png"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      相关资源
      最近更新 更多