用FXML同時顯示兩個JavaFX窗口(最簡單的方式)

Preface

JavaFX顯示多窗口其實是非常簡單的,需要用兩個FXML即可,不用像網上其他人弄的那麼麻煩。

環境:

  • IDEA
  • SceneBuilder V9.0.0

思路

只需要在start() 函數裏面事先primaryStage 一樣的東西即可。

如下代碼:(FXML見後面

Main.java

package sample;

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

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("main.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 600, 400));
        primaryStage.show();


        Stage anotherStage = new Stage();
        Parent anotherRoot = FXMLLoader.load(getClass().getResource("sample.fxml"));
        Scene anotherScene = new Scene(anotherRoot);
        anotherStage.setTitle("Another Window");
        anotherStage.setScene(anotherScene);
        anotherStage.show();
    }

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

運行結果

Display two windows at the same time with FXML

main.fxml

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>


<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/9" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Main">
   <children>
      <Button layoutX="310.0" layoutY="214.0" mnemonicParsing="false" text="Main Button" />
      <Label alignment="CENTER" layoutX="142.0" layoutY="115.0" prefHeight="51.0" prefWidth="70.0" text="Main" textAlignment="CENTER">
         <font>
            <Font size="19.0" />
         </font>
      </Label>
   </children>
</AnchorPane>

sample.fxml

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>


<GridPane alignment="center" hgap="10" vgap="10" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/9" fx:controller="sample.Controller">
   <columnConstraints>
      <ColumnConstraints />
      <ColumnConstraints />
   </columnConstraints>
   <rowConstraints>
      <RowConstraints />
   </rowConstraints>
   <children>
      <AnchorPane prefHeight="329.0" prefWidth="369.0" GridPane.columnIndex="1">
         <children>
            <Button layoutX="201.0" layoutY="180.0" mnemonicParsing="false" text="Test" />
         </children>
      </AnchorPane>
   </children>
</GridPane>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章