gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:02:27 36 4
gpt4 key购买 nike

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

这是 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();
}

接下来,我的另一个类加载,名为“SecondController.java”。在本类(class)中,我使用完全相同的方法 ma​​keFadeIn (但我必须编写两次,因为它不允许我运行程序)。

这是 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);
}

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

最佳答案

您可以将此功能移至基类:

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();
}
}

然后让其他 Controller 扩展它:

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);
}
}

关于java - 如何在两个不同的类中使用相同的方法(JavaFX 和 Scenebuilder)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52393407/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com