JavaFXで新しい子ウィンドウを開く方法
JavaFXで新しい子ウィンドウを開く方法です。Swingとはちょっとやり方が違っていて少し迷いました。
以下のように親ウィンドウのボタンをクリックすると子ウィンドウが現れるようにします。
Swingの場合は親子ともJFrame(またはJDialog)を継承して作り方は全く一緒だったのですが、JavaFXは親ウィンドウがApplicationクラスを、子ウィンドウはStageクラスを継承するようです。で、親ウィンドウは今までどおりstartメソッドで初期設定をする一方で、子ウィンドウはコンストラクタで行います。後者の方が従来のJavaの作法となりますね。
//親ウィンドウ public class ParentForm extends Application{ @Override public void start(Stage stage) throws Exception{ ... } } //子ウィンドウ public class ChaildTest extends Stage { public ChaildTest(Stage stage){ ... } }
ソースコード全文はこちら。まずは親ウィンドウ。
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; public class ParentForm extends Application{ public static void main(String[] args){ launch(args); } @Override public void start(Stage stage) throws Exception{ AnchorPane pane = new AnchorPane(); Scene scene = new Scene(pane,400,150); Button btn = new Button("Open Window"); pane.getChildren().addAll(btn); pane.setTopAnchor(btn, 50.0); pane.setLeftAnchor(btn, 100.0); btn.setOnAction(( ActionEvent ) -> { System.out.println("OK"); ChaildTest f = new ChaildTest(stage); }); stage.setScene(scene); stage.show(); } }
次に子ウィンドウ。
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.stage.Stage; public class ChaildTest extends Stage { public ChaildTest(Stage stage){ Label label = new Label("Child Window"); HBox pane = new HBox(); pane.getChildren().add(label); Scene scene = new Scene(pane, 300, 200); this.setScene(scene); this.show(); } }
スポンサーリンク