您的位置:首页 > 编程语言 > Java开发

用FXML同时显示两个JavaFX窗口(最简单的方式)

2018-01-16 17:49 2361 查看

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


运行结果



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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息