Java 为什么这会打乱我的计划?

Java 为什么这会打乱我的计划?,java,Java,我已经查看了所有来自旧代码的注释和注释,但我不明白为什么它不起作用 import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javaf

我已经查看了所有来自旧代码的注释和注释,但我不明白为什么它不起作用

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import java.util.Stack;
import javafx.scene.layout.VBox;

public class Main extends Application{

    Stage window;//makes window a stage
    Scene scene1, scene2;//makes scene1 and scene2 into Scene's
        public static void main(String []args) {

        //launches the main 
        launch(args);
    }
    @Override//Overrides Application
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;//Makes window primary stage
        Label label1 = new Label ("This is the first scene!");//Makes a label
        Button button1 = new Button();//Declares button as a Button
        button1.setText("Click me for Scene 2");//Sets the text of the button
        button1.setOnAction(e -> window.setScene(scene2));
        //This say, on the action, change the scene

        VBox layout1 = new VBox(20);//Makes layout1 into a VBox 
        layout1.getChildren().addAll(label1, button1);//Adds the 'Children'
        scene1 = new Scene(layout1, 500, 400);//Sets up layout1

        Button button2 = new Button();//makes a second button
        button2.setText("Click me for scene 1");//sets the text for button2
        button2.setOnAction(e -> window.setScene(scene1));//When button 2 is click, it changes scene

        StackPane layout2 = new StackPane();//Makes a new StackPane layout
        layout2.getChildren().add(button2);//Adds button2 to the layout
        scene2 = new Scene (layout2, 500, 400);//Gives arguemnts for Scene2

        window.setScene(scene1);//Sets scene of the window stage 
        window.setTitle("This is a title");//Sets title
        window.show();//Shows the window

    }
}
Vs

我在这两个词之间唯一的改变就是加上了“场景”这个词:

场景1=新场景。。。。工作

vs

场景场景2=新场景。。。。不起作用。这是为什么?

您是,并在第二个代码中将它们保留为null

换句话说,第一个代码中只有2个场景实例,另一个代码中只有4个

执行此操作时,它使用Main.this.scene2,而不是本地实例

button1.setOnAction(e -> window.setScene(scene2));

如果确实需要使用本地实例,则需要在设置操作侦听器之前将其声明为final并进行初始化

将场景放在它们前面不起作用的原因是,您已经将它们声明为行中的场景,但没有初始化它们 场景一,场景二 所以您不需要再次指定它。 这就像是一个整数inta,然后初始化它inta=1。这没有意义,因为a已经被定义为int。
事实上,它很少不起作用,更多的是没有意义。

你能详细说明你所说的“起作用”和“不起作用”是什么意思吗?你在这里发布了很多代码,不知道你看到了什么错误,也不知道你做了什么来修复它,我们很难提供任何有用的反馈。它不起作用,因为本地场景初始化发生在操作初始化按钮之后,这意味着lambda表达式中引用的scene1和scene2是类级变量。颠倒初始化顺序也确实可以解决问题
button1.setOnAction(e -> window.setScene(scene2));