如何在两个不同的 类(带有 Scenebuilder 的 JavaFX)中使用相同的方法?

How to use same method in two different classes (JavaFX with Scenebuilder)?

我目前正在 eclipse 中尝试使用 JavaFXSceneBuilder 来创建和设计我自己的程序。在我的第一个 class "StartController" 中,我使用了一种名为 makeFadeIn 的方法。基本上,当我单击一个按钮时,另一个页面会加载淡入淡出效果。

这是来自 StartController.java 的代码(注意 makeFadeIn):

public class StartController {

@FXML
private AnchorPane rootPane;

private void makeFadeIn() {
    FadeTransition fadeTransition = new FadeTransition();
    fadeTransition.setDuration(Duration.millis(1000));
    fadeTransition.setNode(rootPane);
    fadeTransition.setFromValue(0);
    fadeTransition.setToValue(1);
    fadeTransition.play();
}

@FXML
private void loadSecondPage(ActionEvent event) throws IOException {
    AnchorPane startPage = FXMLLoader.load(getClass().getResource("SecondController.fxml"));
    rootPane.getChildren().setAll(startPage);
    makeFadeIn();
}

接下来,我的另一个 class 加载名为 "SecondController.java"。在这个class中,我使用了完全相同的方法makeFadeIn(但我不得不写两次,因为它不允许我运行程序) .

这是来自 SecondController.java 的代码:

public class SecondController {

@FXML
private AnchorPane rootPane;

private void makeFadeIn() {
    FadeTransition fadeTransition = new FadeTransition();
    fadeTransition.setDuration(Duration.millis(1000));
    fadeTransition.setNode(rootPane);
    fadeTransition.setFromValue(0);
    fadeTransition.setToValue(1);
    fadeTransition.play();
}

@FXML
private void loadFirstPage(ActionEvent event) throws IOException {
    AnchorPane startPage = FXMLLoader.load(getClass().getResource("StartController.fxml"));
    rootPane.getChildren().setAll(startPage);
}

我的问题是:我能否以某种方式从第一个 class 调用 makeFadeIn 方法,这样我就不必在第二个 class 中编写它?我想我需要以某种方式继承它,但我不确定如何继承。我尝试将其声明为 public 而不是私有的,但这并没有多大帮助。

您可以将此功能移动到基础 class:

public class BaseController {

    @FXML
    private AnchorPane rootPane;

    protected AnchorPane getRootPage() {
        return rootPane;
    }

    protected void makeFadeIn() {
        FadeTransition fadeTransition = new FadeTransition();
        fadeTransition.setDuration(Duration.millis(1000));
        fadeTransition.setNode(rootPane);
        fadeTransition.setFromValue(0);
        fadeTransition.setToValue(1);
        fadeTransition.play();
    }
}

然后让其他控制器扩展它:

public class StartController extends BaseController {

    @FXML
    private void loadSecondPage(ActionEvent event) throws IOException {
        AnchorPane startPage = 
            FXMLLoader.load(getClass().getResource("SecondController.fxml"));
        getRootPane().getChildren().setAll(startPage);
        makeFadeIn();
    }
}

public class SecondController extends BaseController {

    @FXML
    private void loadFirstPage(ActionEvent event) throws IOException {
        AnchorPane startPage = 
            FXMLLoader.load(getClass().getResource("StartController.fxml"));
        getRootPane().getChildren().setAll(startPage);
    }
}