在JavaFX中执行setImage时发生NullPointerException

时间:2019-05-27 09:09:57

标签: java intellij-idea javafx fxml scenebuilder

我正在设置Java应用程序,并且正在使用JavaFX + SceneBuilder。 FXML链接到控制器类(PlayerViewGUI),而屏幕本身由于另一个类(RemoteViewGUI)而显示。我想在窗格中加载一些图像,但得到NullPointerException和RuntimeException。

请注意,由于FXML文件中的fx:controller标签,我将Controller链接到PlayerViewGUI,并且在FXML文件中也引用了imageView1。此外,我尝试使用每种指令或技术来引用路径"/assets/cards/weapon_1.png"上的图像。资产目录包含在资源目录(标记为目录)中。奇怪的是,成功加载了FXML(包含在资源目录的/fxml目录中)而没有成功加载武器。

public class RemoteViewGUI extends Application {

@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("/fxml/chooseWeapon.fxml"));
    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
    new PlayerViewGUI().buildChooseScreen(stage);
    }

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

//This is the beginning of the Controller class
public class PlayerViewGUI {
@FXML
private ImageView imageView1;
public void buildChooseScreen(Stage stage)
{
    String url="/assets/cards/weapon_1.png";
    System.out.println(url);
    imageView1.setImage(new Image(getClass().getResource(url).toExternalForm()));
} }

我尝试使用: imageView1.setImage(new Image(url)); imageView1.setImage(new Image("file:assets/card/weapon_1.png")); imageView1.setImage(new Image("file:/assets/card/weapon_1.png")); 尽管如此,我经常会收到RuntimeException和NullPointerException,有时会收到“找不到无效的URL”或类似的内容(这取决于我用来检索图像的指令)。

FXML文件为:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.TitledPane?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.HBox?>

<TitledPane alignment="CENTER" collapsible="false" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="535.0" prefWidth="800.0" text="Choose a weapon by clicking on it" xmlns="http://javafx.com/javafx/8.0.172-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="it.polimi.se2019.view.PlayerViewGUI">
   <content>
      <HBox alignment="CENTER">
         <children>
            <ImageView fx:id="imageView1" fitHeight="460.0" fitWidth="240.0" pickOnBounds="true" preserveRatio="true" />
            <ImageView fx:id="imageView2" fitHeight="460.0" fitWidth="240.0" pickOnBounds="true" preserveRatio="true" />
            <ImageView fx:id="imageView3" fitHeight="460.0" fitWidth="240.0" pickOnBounds="true" preserveRatio="true" />
         </children>
      </HBox>
   </content>
</TitledPane>

0 个答案:

没有答案