0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JavaFX の InvocationTargetExceptionを治す

Last updated at Posted at 2023-10-10

環境

InteliJ IDEA
JDK21
ビルドツールとしてMavenを使用

問題

以下のような
・TestWindow.java
・TestWindowController.java
・test-view.fxml
の3ファイルで構成されている単純なJavaFXアプリケーションをTestWindow#main()から実行すると、InvocationTargetExceptionがスローされる。

実行イメージ
image.png

TestWindow.java
package com.example.hoge;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class TestWindow extends Application {
   @Override
   public void start(Stage stage) throws IOException {
       FXMLLoader fxmlLoader = new FXMLLoader(TestWindow.class.getResource("test-view.fxml"));
       Scene scene = new Scene(fxmlLoader.load(), 320, 240);
       stage.setTitle("Hello!");
       stage.setScene(scene);
       stage.show();
   }

   public static void main(String[] args) {
       launch(args);
   }
}
TestWindowController.java
package com.example.hoge;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;

public class TestWindowController {
    @FXML
    private Label textView;

    @FXML
    public void onHelloButtonClick(ActionEvent actionEvent) {
        System.out.println("click");
    }
}

test-view.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>

<?import javafx.scene.control.Button?>
<VBox alignment="CENTER" spacing="20.0" xmlns:fx="http://javafx.com/fxml"
      fx:controller="com.example.hoge.TestWindowController">
    <padding>
        <Insets bottom="20.0" left="20.0" right="20.0" top="20.0"/>
    </padding>

    <Label fx:id="textView"/>
    <Button text="Hello!" onAction="#onHelloButtonClick"/>
</VBox>

解決策

module-info.javaに以下の内容を追記する

module-info.java
com.example {
    // ...(略)...
    // reuires が色々...
    opens com.example.hoge to javafx.fxml;
    exports com.example.hoge;
}

備考

java.lang.reflect.InvocationTargetExceptionは一般的な例外であり、JavaFX関連だけでも様々な原因が考えられます。適宜他情報源の参照もお願いします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?