如何在两个不同的类(带有Scenebuilder的JavaFX)中使用相同的方法?
我目前正在eclipse中试用JavaFX和SceneBuilder来创建和设计我自己的程序。在我的第一堂课“StartController”中,我使用了一个名为makeFadeIn的方法。基本上,当我点击一个按钮时,另一个页面会加载淡入淡出效果 这是StartController.java(注意makeFadeIn)中的代码: 接下来,我的另一个类被加载,名为“SecondController.java”。在这个类中,我使用了完全相同的方法makeFadeIn(但是我不得不写两次,因为它不允许我运行程序) 这是SecondController.java中的代码:如何在两个不同的类(带有Scenebuilder的JavaFX)中使用相同的方法?,java,eclipse,inheritance,javafx,scenebuilder,Java,Eclipse,Inheritance,Javafx,Scenebuilder,我目前正在eclipse中试用JavaFX和SceneBuilder来创建和设计我自己的程序。在我的第一堂课“StartController”中,我使用了一个名为makeFadeIn的方法。基本上,当我点击一个按钮时,另一个页面会加载淡入淡出效果 这是StartController.java(注意makeFadeIn)中的代码: 接下来,我的另一个类被加载,名为“SecondController.java”。在这个类中,我使用了完全相同的方法makeFadeIn(但是我不得不写两次,因为它不允许
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方法,这样就不必在第二个类中编写它?我想我需要以某种方式继承它,但我不确定如何继承。我尝试将其声明为public而不是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();
}
}
然后让其他控制器扩展它:
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);
}
}
当我遇到类似情况时,我会创建一个实用程序类来提供帮助。
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);
}
}