简体   繁体   English

用一个替换多个控制器 (JavaFX)

[英]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我使用 Gloun SceneBuilder 设计了几个 GUI,这意味着每个 GUI 表单都有自己的控制器 例如:AddBookForm.fxml 将有 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 EditBookForm.fxml 将有 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?所以我想将两个 GUI 的控制器合二为一,一个我命名为 BookController(它将有 AddBook 和 EditBook 按钮处理程序)所以所有的书籍事件都将进入一个控制器而不是单独的控制器这可能吗? and if so, how?如果是这样,怎么办? \I saw that it could be related to lambda, but I really don't get it.. \我看到它可能与 lambda 有关,但我真的不明白..

You can simple set the same controller to the two fxml files 1 :您可以简单地将同一控制器设置为两个fxml文件1

A.fxml一个.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 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) Controller.java (两者都使用)

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 1每个fxml使用不同的Controller实例,因此它不是共享的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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