一、问题描述
新建JavaFx项目,将图片都粘贴到resources同一文件夹下,只有一张图片可以正常运行出来,其他都不得,很奇怪。运行程序时出现如下图爆红:
package com.example.fxtest2;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.ImageCursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.Dragboard;
import javafx.scene.input.KeyCode;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Border;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
public class HelloApplication extends Application {
@Override
public void start(Stage stage) throws IOException {
AnchorPane pane=new AnchorPane();
ImageView imageView=new ImageView();
//Image image=new Image("iconWrite.png");
//Image image=new Image("girl.png");
//Image image=new Image("resources/girl.png");
Image image=new Image("girl.png");
imageView.setImage(image);
pane.getChildren().add(imageView);
Scene scene=new Scene(pane,1000,600);
stage.setScene(scene);
stage.show();
/* URL resource=getClass().getResource("");
System.out.println(resource.toString());
System.exit(0);*/
}
@Override
public void init() throws Exception {
super.init();
System.out.println("init()...");//先调用
}
@Override
public void stop() throws Exception {
super.stop();
System.out.println("stop()...");//窗口关闭自动调用
}
public static void main(String[] args) {
launch();
}
}
二、解决方法
经过前辈指导,可以用几种方法处理该问题,关于配置的方法个人还不太理解,暂不分享。以下分享两种较简单有效的解决操作:
方法一:左上角文件-项目结构-模块,将src下的resources设置为源:
方法二:左上角文件-设置-构建、执行、部署-构建工具-Maven,对“Maven主路径”进行选择,不要用项目默认的:
三、运行结果
解决问题后,运行效果如下图