Я понимаю, что это очень старое сообщение и уже есть отличные ответы, но я хотел сделать простой MCVE, чтобы продемонстрировать один такой подход и позволить новым кодеру быстро увидеть концепцию в действии.
blockquote>В этом примере мы будем использовать 5 файлов:
- Main.java - просто используется для запуска приложения и вызова первого контроллера.
- Controller1.java - контроллер для первого макета FXML.
- Controller2.java - контроллер для второго макета FXML.
- Layout1.fxml - макет FXML для первого сцена.
- Layout2.fxml - макет FXML для второй сцены.
Все файлы перечислены полностью в нижней части этого сообщения.
Цель: показать переданные значения от
Controller1
доController2
и наоборот.Поток программы:
- Первая сцена содержит
TextField
,Button
иLabel
. Когда щелчокButton
щелкнут, второе окно загружается и отображается, включая текст, введенный вTextField
.- Внутри второй сцены есть также
TextField
,Button
, иLabel
.Label
отобразит текст, введенный вTextField
на первой сцене.- При вводе текста во второй сцене
TextField
и нажатииButton
первая сценаLabel
сцены обновлен, чтобы показать введенный текст.Это очень простая демонстрация и, безусловно, может означать некоторое улучшение, но должна сделать концепцию очень понятной.
Сам код также комментируется некоторые детали того, что происходит и как.
КОД
blockquote>Main.java:
import javafx.application.Application; import javafx.stage.Stage; public class Main extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { // Create the first controller, which loads Layout1.fxml within its own constructor Controller1 controller1 = new Controller1(); // Show the new stage controller1.showStage(); } }
Controller1.java:
import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.stage.Stage; import java.io.IOException; public class Controller1 { // Holds this controller's Stage private final Stage thisStage; // Define the nodes from the Layout1.fxml file. This allows them to be referenced within the controller @FXML private TextField txtToSecondController; @FXML private Button btnOpenLayout2; @FXML private Label lblFromController2; public Controller1() { // Create the new stage thisStage = new Stage(); // Load the FXML file try { FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout1.fxml")); // Set this class as the controller loader.setController(this); // Load the scene thisStage.setScene(new Scene(loader.load())); // Setup the window/stage thisStage.setTitle("Passing Controllers Example - Layout1"); } catch (IOException e) { e.printStackTrace(); } } /** * Show the stage that was loaded in the constructor */ public void showStage() { thisStage.showAndWait(); } /** * The initialize() method allows you set setup your scene, adding actions, configuring nodes, etc. */ @FXML private void initialize() { // Add an action for the "Open Layout2" button btnOpenLayout2.setOnAction(event -> openLayout2()); } /** * Performs the action of loading and showing Layout2 */ private void openLayout2() { // Create the second controller, which loads its own FXML file. We pass a reference to this controller // using the keyword [this]; that allows the second controller to access the methods contained in here. Controller2 controller2 = new Controller2(this); // Show the new stage/window controller2.showStage(); } /** * Returns the text entered into txtToSecondController. This allows other controllers/classes to view that data. */ public String getEnteredText() { return txtToSecondController.getText(); } /** * Allows other controllers to set the text of this layout's Label */ public void setTextFromController2(String text) { lblFromController2.setText(text); } }
Controller2.java:
import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.stage.Stage; import java.io.IOException; public class Controller2 { // Holds this controller's Stage private Stage thisStage; // Will hold a reference to the first controller, allowing us to access the methods found there. private final Controller1 controller1; // Add references to the controls in Layout2.fxml @FXML private Label lblFromController1; @FXML private TextField txtToFirstController; @FXML private Button btnSetLayout1Text; public Controller2(Controller1 controller1) { // We received the first controller, now let's make it usable throughout this controller. this.controller1 = controller1; // Create the new stage thisStage = new Stage(); // Load the FXML file try { FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout2.fxml")); // Set this class as the controller loader.setController(this); // Load the scene thisStage.setScene(new Scene(loader.load())); // Setup the window/stage thisStage.setTitle("Passing Controllers Example - Layout2"); } catch (IOException e) { e.printStackTrace(); } } /** * Show the stage that was loaded in the constructor */ public void showStage() { thisStage.showAndWait(); } @FXML private void initialize() { // Set the label to whatever the text entered on Layout1 is lblFromController1.setText(controller1.getEnteredText()); // Set the action for the button btnSetLayout1Text.setOnAction(event -> setTextOnLayout1()); } /** * Calls the "setTextFromController2()" method on the first controller to update its Label */ private void setTextOnLayout1() { controller1.setTextFromController2(txtToFirstController.getText()); } }
Layout1.fxml:
<?xml version="1.0" encoding="UTF-8"?> <?import javafx.geometry.Insets?> <?import javafx.scene.control.*?> <?import javafx.scene.layout.AnchorPane?> <?import javafx.scene.layout.HBox?> <?import javafx.scene.layout.VBox?> <AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1"> <VBox alignment="CENTER" spacing="10.0"> <padding> <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/> </padding> <Label style="-fx-font-weight: bold;" text="This is Layout1!"/> <HBox alignment="CENTER_LEFT" spacing="10.0"> <Label text="Enter Text:"/> <TextField fx:id="txtToSecondController"/> <Button fx:id="btnOpenLayout2" mnemonicParsing="false" text="Open Layout2"/> </HBox> <VBox alignment="CENTER"> <Label text="Text From Controller2:"/> <Label fx:id="lblFromController2" text="Nothing Yet!"/> </VBox> </VBox> </AnchorPane>
Layout2.fxml:
<?xml version="1.0" encoding="UTF-8"?> <?import javafx.geometry.Insets?> <?import javafx.scene.control.*?> <?import javafx.scene.layout.AnchorPane?> <?import javafx.scene.layout.HBox?> <?import javafx.scene.layout.VBox?> <AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1"> <VBox alignment="CENTER" spacing="10.0"> <padding> <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/> </padding> <Label style="-fx-font-weight: bold;" text="Welcome to Layout 2!"/> <VBox alignment="CENTER"> <Label text="Text From Controller1:"/> <Label fx:id="lblFromController1" text="Nothing Yet!"/> </VBox> <HBox alignment="CENTER_LEFT" spacing="10.0"> <Label text="Enter Text:"/> <TextField fx:id="txtToFirstController"/> <Button fx:id="btnSetLayout1Text" mnemonicParsing="false" text="Set Text on Layout1"/> </HBox> </VBox> </AnchorPane>