JavaFX8+FXMLで開発をしているのですが、親ウインドウから新規ウインドウを起動、そしてその新規ウインドウ中にあるボタンにButton.setOnActionメソッドでイベントを追加したいのですが、どうやれば良いのか分かりません。
とりあえず、こちらのサイトを見ながらやったところ、新規ウインドウを表示することは出来ましたが、新規ウインドウ中にあるボタンへのイベント登録を試すとNullPointerExceptionが発生してしましました。(つまりbuttonはnull)
lang
1// NewWindowTest.java 2import javafx.application.Application; 3import javafx.fxml.FXMLLoader; 4import javafx.scene.Parent; 5import javafx.scene.Scene; 6import javafx.stage.Stage; 7 8public class NewWindowTest extends Application { 9 @Override 10 public void start(Stage stage) throws Exception { 11 FXMLLoader loader = new FXMLLoader(getClass().getResource("OwnerFXML.fxml")); 12 Parent root = loader.load(); 13 14 OwnerFXMLController controller = (OwnerFXMLController) loader.getController(); 15 controller.setOwnerStage(stage); 16 17 Scene scene = new Scene(root); 18 19 stage.setScene(scene); 20 stage.show(); 21 } 22 23 public static void main(String[] args) { 24 launch(args); 25 } 26}
lang
1// OwnerFXMLController.java 2import java.io.IOException; 3import java.net.URL; 4import java.util.ResourceBundle; 5import javafx.fxml.FXML; 6import javafx.fxml.FXMLLoader; 7import javafx.fxml.Initializable; 8import javafx.scene.control.Button; 9import javafx.scene.Scene; 10import javafx.stage.Stage; 11 12public class OwnerFXMLController implements Initializable { 13 @FXML 14 Button button; 15 16 Stage ownerStage; 17 18 @Override 19 public void initialize(URL url, ResourceBundle rb) { 20 try { 21 // 新規ウインドウの表示 22 Scene newScene = new Scene(FXMLLoader.load(getClass().getResource("NewFXML.fxml"))); 23 Stage newStage = new Stage(); 24 newStage.initOwner(ownerStage); // 親のStageを登録 25 newStage.setScene(newScene); 26 newStage.show(); // 表示 27 newStage.toFront(); // ウインドウを前面に移動 28 29 // NullPointerException が発生する 30 button.setOnAction(e -> System.out.println("クリックされました")); 31 } catch (IOException ex) { 32 } 33 } 34 35 void setOwnerStage(Stage stage) { 36 ownerStage = stage; 37 } 38}
lang
1<!-- OwnerFXML.fxml --> 2<?xml version="1.0" encoding="UTF-8"?> 3 4<?import java.lang.*?> 5<?import java.util.*?> 6<?import javafx.scene.*?> 7<?import javafx.scene.control.*?> 8<?import javafx.scene.layout.*?> 9 10<AnchorPane prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1" fx:controller="OwnerFXMLController"> 11 <children> 12 <Label text="親ウインドウ" /> 13 </children> 14</AnchorPane>
lang
1<!-- NewFXML.fxml --> 2<?xml version="1.0" encoding="UTF-8"?> 3 4<?import java.lang.*?> 5<?import java.util.*?> 6<?import javafx.scene.*?> 7<?import javafx.scene.control.*?> 8<?import javafx.scene.layout.*?> 9 10<AnchorPane prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1"> 11 <children> 12 <Label text="新規ウインドウ" /> 13 <Button text="ボタン" fx:id="button" /> 14 </children> 15</AnchorPane>
JavaFX8+FXMLで生成した新規ウインドウのNodeを親のコントローラから取得する方法(今回の場合はButton)を知っていらっしゃる方、ご回答よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2015/03/23 08:32