简体   繁体   中英

Replacing multiple controllers with one (JavaFX)

I've designed a several GUI's using Gloun SceneBuilder Which means each and every GUI form will have its own contoller For Example: AddBookForm.fxml will have AddBookController.java

    import javafx.fxml.FXML;
import javafx.scene.control.Button;

public class AddBookController {

    @FXML
    private Button btnAddBook;

    @FXML
    void AddBook(MouseEvent event) {

    }

}

EditBookForm.fxml will have EditBookController

    import javafx.fxml.FXML;
import javafx.scene.control.Button;

public class PleaseProvideControllerClassName {

    @FXML
    private Button btnEditBook;

    @FXML
    void editBook(MouseEvent event) {

    }

}

So I would like to have both of the GUI's controllers into one, one I'd name BookController (It would have AddBook and EditBook button handlers) So all books events would be into one controller instead of separate ones Is that possible? and if so, how? \I saw that it could be related to lambda, but I really don't get it..

You can simple set the same controller to the two fxml files 1 :

A.fxml

<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.HBox?>

<HBox xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Controller">
   <children>
      <Button fx:id="buttonA" onAction="#buttonAClicked" text="A" textAlignment="CENTER" />
   </children>
</HBox>

B.fxml

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.HBox?>

<HBox xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="src.tests.xml.Controller">
   <children>
      <Button fx:id="buttonB" onAction="#buttonBClicked" text="B" textAlignment="CENTER" />
   </children>
</HBox>

Controller.java (used by both)

import javafx.fxml.FXML;
import javafx.scene.control.Button;

public class Controller{

    @FXML
    private Button buttonA, buttonB;

    public void buttonAClicked(){
        System.out.println("Button A clicked");
    }

    public void buttonBClicked(){
        System.out.println("Button B clicked");
    }
}


1 Each fxml uses a different instance of Controller so it is not a shared one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM