使用我在查看 this answer 时学到的东西,我想实现一个自定义 Pane 。此 Pane 称为“BackgroundEffectPane”,其主要用途是获取效果并将其仅应用于背景。这将使我能够以更简洁的方式在链接的答案中实现半透明背景 StackPane。
到目前为止,我已经通读了 Pane 的文档和 Node 。到目前为止,我还没有看到任何明显的方法可以覆盖以尽可能干净地完成此操作。唯一让我觉得相关的是getChildren() Pane 中的方法。
这是覆盖的正确做法吗?
Pane 是子类的正确类吗?
TLDR:尝试创建自定义 Pane ,我要覆盖哪些方法。我想做的就是为背景添加效果。
最佳答案
我不会为此重写任何方法。如果您想创建提供此功能的 StackPane
子类,只需在构造函数中调用 getChildren().addAll(...)
即可:
public class BackgroundEffectPane extends StackPane {
public BackgroundEffectPane(Node content) {
getChildren().addAll(createBackground(), freeze(...), content);
}
// code refactored from other answer...
}
当然,现在您根本不再需要子类化:
public class BackgroundEffectPane {
private final Node content ;
private final Parent effectPane ;
public BackgroundEffectPane(Node content) {
this.content = content ;
this.effectPane = new StackPane(createBackground(), freeze(...), content);
}
public Parent getEffectPane() {
return effectPane ;
}
// other code...
}
通过不暴露具有效果的 Pane 的底层实现(即 API 不会暴露您正在使用 StackPane
),更好地封装了类。
关于java - 在 JavaFX 中扩展 Pane ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40547987/