作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我目前正在 eclipse 中尝试使用 JavaFX 和 SceneBuilder 来创建和设计我自己的程序。在我的第一个类“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();
}
接下来,我的另一个类加载,名为“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);
}
我的问题是:我可以以某种方式从第一个类调用 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/
我是一名优秀的程序员,十分优秀!