タツノオトシゴのブログ

主にJavaに関するものです。

FXMLからNodeのインスタンスの作成方法について

FXMLLoaderクラスを利用したFXMLからSceneやPaneのインスタンスの作成方法は、大きく分けて3つあります。

(1)SceneやPaneのみのインスタンスを取得する場合

Controllerを伴わないSceneやPaneのインスタンスをFXMLから取得する場合、staticメソッドのFMLLoader#load(...)を利用します。

/*
 * 呼び出そうとしているFXMLファイルが、クラスパス上の呼び出し側のクラスと同じ場所にある場合
 * 相対パスである、自身のクラスのgetClass().getResoruce("ファイル名")を指定します。
 */
AnchorPane pane = (AnchorPane) FXMLLoader.load(getClass().getResource("SamplePane.fxml"));

/*
 * 呼び出そうとしているFXMLファイルをクラスパス上の絶対パスで指定する場合は、
 * staticなgetResource(...)を呼び出します。
 */
AnchorPane pane = (AnchorPane) FXMLLoader.load(SampleClass.class.getResource("/sample/gui/SamplePane.fxml"));

(2)Controllerを伴うSceneやPaneのインスタンスを取得する場合

FXMLの属性「fx:controller="Controllerのクラスパス"」を指定している場合は、SceneやControllerのインスタンスを別々に取得します。

FXMLのサンプル
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.collections.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>

<AnchorPane id="" fx:id="" " xmlns:fx="http://javafx.com/fxml" fx:controller="sample.gui.SamplePaneController">
・・・(省略)・・・
</AnchorPane>
PaneとControllerのインスタンスの取得

FXMLLoaderのインスタンスを作成して、FXMLLoader#getController()メソッドでコントローラのインスタンスを取得します。

FXMLLoader loader = new FXMLLoader();

// staticメソッドは異なり、InputStream形式なので、Class#getResourceAsStreamから値を取得する
AnchorPane sample = (AnchorPane) loader.load(getClass().getResourceAsStream("SamplePane.fxml"));

// 絶対パスで指定するときには、staticなgetResourceAsStream(...)を呼び出します。
//AnchorPane sample = (AnchorPane) loader.load(SampleClass.class.getResourceAsStream("/sample/gui/SamplePane.fxml"));

// Controllerの取得
SamplePaneController controller = loader.getController();

(3)コンポーネント(自身がController)の場合

FXMLのルート要素が「」を設定している場合は、SceneやControllerのインスタンスを同時に取得します。
Controller自体、Paneなどを継承して定義します。

FXMLのサンプル
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.VBox?>

<fx:root type="VBox" xmlns:fx="http://javafx.com/fxml">
   ・・・(省略)・・・
</fx:root>
ControllerとFXMLのロード方法

FXMLのtype属性で指定したクラスを継承します。
コンストラクタにて、自身をrootノード、controllerに指定します。
この方法の場合、Javaクラスのインスタンスを作成するだけで、FXMLも同時にロードされます。

public class SamplePane extends VBox {
    public SamplePane() {
        final FXMLLoader fxmlLoader = new FXMLLoader(
                getClass().getClassLoader().getResource("/sample/SampePane.fxml"));
        fxmlLoader.setRoot(this);
        fxmlLoader.setController(this);
        fxmlLoader.load();
    }
   ・・・(省略)・・・
}