是否可以将JavaFX和JavaFXML屏幕合并到一个项目中,而我可以从使用场景生成器构建的屏幕切换到下一个屏幕却使用JavaFX构建该项目?
答案 0 :(得分:0)
请注意,与以编程方式调用屏幕或场景构建器生成的fxml文件没有区别。您可以从代码或fxml启动第一个窗口,然后从代码或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("sample.fxml"));
primaryStage.setTitle("Hello World");
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller.java
package sample;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Controller {
@FXML
private javafx.scene.control.Button myButton;
@FXML
private void testButton(ActionEvent e) {
System.out.println("Button Clicked...");
Stage currentStage = (Stage) myButton.getScene().getWindow();
Group root = new Group();
Stage stage = new Stage();
stage.setTitle("My New Stage Title");
stage.setScene(new Scene(root, 450, 450));
stage.show();
// Hide this current window (if this is what you want)
currentStage.close();
}
}
sample.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<children>
<Button fx:id="myButton" layoutX="57.0" layoutY="59.0" mnemonicParsing="false" onAction="#testButton" text="Click me!" />
</children>
</AnchorPane>
代码说明: 使用按钮启动一个初始窗口,在Controller类中声明按钮id和onAction来启动另一个窗口,然后关闭初始窗口。如果您不想隐藏初始屏幕,只需将其注释掉即可。