我正在学习 javafx,我已经完成了基础知识,所以现在我想做一个更复杂的项目。我在网上阅读了很多关于这个主题的指南,但我找不到任何地方如何在每个类代表 1 个场景时切换场景或更改根节点。
为了更好地理解这里是我的项目的简化版本:
假设我有 3 个类 A、B 和 C:
public class A{
private Stage stage;
A(Stage stage){
this.stage = stage;
}
public void showGui(){
// This will make all elements, put them on scene and then set that scene to stage
}
public void callB(){
B b = new B(Stage);
b.showGui();
}
}
public class B{
private Stage stage;
B(Stage stage){
this.stage = stage;
}
public void showGui(){
// This will make all elements, put them on scene and then set that scene to stage
}
public void callC(){
C c = new C(Stage);
c.showGui();
}
}
public class C{
// This is completely same as other two, it calls A so those 3 form some sort of circle.
}
在 public void start(Stage primaryStage) 中的程序开始时,我创建了 A 的对象并将其传递给初级阶段,然后在每个类中更改它,它工作正常。但我对此有几个问题:
这是正确的做法吗?
有没有其他方法可以在保持类的同时做到这一点,或者我应该只在主课中做所有事情?
是不是先传Scene再换根节点比较好?
对不起,如果我问的有点多,但我阅读了很多关于它仍然找不到任何可以帮助我的东西,所以这是我最后的解决方案。
最佳答案
您可以在此处进行一些设计改进:
您的类根本不需要了解
Stage
和其他类,参见hiding concept ——他们知道的越少,你的程序就越不复杂。场景的根节点就足够了。您甚至可以覆盖 Node 以避免额外的代码。您的类(class)看起来非常相似。您可能希望引入父抽象类并将所有切换逻辑委托(delegate)给单个方法(这样,如果您的逻辑发生变化,您就不需要更改所有类)
看下一个例子:
public class FxThreeNodes extends Application {
private abstract class CycledView extends StackPane { // Choose whatever is most appropriate class
CycledView(CycledView next) {
this.next = next;
createGUI();
}
abstract void createGUI();
protected void callNext() {
getScene().setRoot(next);
}
private CycledView next;
}
// Here you implement diffent GUIs for A, B and C
private class A extends CycledView {
public A(CycledView next) {
super(next);
}
void createGUI() {
getChildren().add(new Button("I'm A") {
@Override
public void fire() {
callNext();
}
});
}
}
private class B extends CycledView {
public B(CycledView next) {
super(next);
}
void createGUI() {
getChildren().add(new Button("This is B") {
@Override
public void fire() {
callNext();
}
});
}
}
private class C extends CycledView {
public C(CycledView next) {
super(next);
}
void createGUI() {
getChildren().add(new Button("Greeting from C") {
@Override
public void fire() {
callNext();
}
});
}
}
@Override
public void start(Stage primaryStage) {
CycledView c = new C(null);
CycledView b = new B(c);
CycledView a = new A(b);
c.next = a;
Scene scene = new Scene(a, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
关于java - 如何在没有 FXML 的情况下在 JavaFX 中正确切换场景/更改场景的根节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43761138/