在没有FXML的情况下,如何在JavaFX中正确切换场景/更改场景的根节点?
我正在学习javafx,我已经完成了基础知识,所以现在我想做一个更复杂的项目。我在网上读了很多关于这个主题的指南,但是我找不到任何地方当每个类代表一个场景时如何切换场景或更改根节点。在没有FXML的情况下,如何在JavaFX中正确切换场景/更改场景的根节点?,java,javafx,javafx-8,Java,Javafx,Javafx 8,我正在学习javafx,我已经完成了基础知识,所以现在我想做一个更复杂的项目。我在网上读了很多关于这个主题的指南,但是我找不到任何地方当每个类代表一个场景时如何切换场景或更改根节点。 为了更好地理解,这里是我的项目的简化版本: 假设我有3个等级A、B和C: public class A{ private Stage stage; A(Stage stage){ this.stage = stage; } public void showGui()
为了更好地理解,这里是我的项目的简化版本:
假设我有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)我制作了一个对象,并通过了它的初级阶段,然后在每个类中我都更改了它,它工作得很好。但我对此没有什么问题:这是正确的做法吗?
在上课的时候还有其他方法吗?还是我应该在主课堂上做所有的事情?
传递场景然后更改根节点是否更好
对不起,如果我问得太多了,但是我读了很多关于它的书,仍然找不到任何可以帮助我的东西,所以这是我最后的解决方案。您可以在这里进行一些设计改进:
Stage
和其他类,请参见——它们知道的越少,您的程序就越不复杂。场景的根节点就足够了。您甚至可以重写节点以避免额外的代码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);
}
}
谢谢,这对我很有帮助。根据规则,问题应该避免一次问多个直接问题。此外,如果Sergey满意地回答了您的问题,您应该将其标记为“已接受”。