用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);
    }
}

运行结果

用FXML同时显示两个JavaFX窗口(最简单的方式)_第1张图片

main.fxml









<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










<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>

你可能感兴趣的:(JavaFX)