我想换到另一个班级的场景,但我遇到了很大困难。
现在我可以移动到第二个屏幕没问题,但是回到第一个屏幕会给我 NullPointerException 。
非常感谢帮助。非常感谢提前。
主要类
public class Main extends Application {
Stage ps;
Group root = new Group();
Scene s = new Scene(root, 300, 300, Color.AQUA);
Controller con = new Controller();
public void start(Stage primaryStage) throws Exception {
ps = primaryStage;
con.buttonLayout();
buttonLayout();
primaryStage.setTitle("Hello World");
ps.setScene(s);
primaryStage.show();
}
public void buttonLayout() {
Button but = new Button("first");
but.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
ps.setScene(con.s);
}
});
root.getChildren().add(but);
}
public static void main(String[] args) {
launch(args);
}
}
其他课程
public class Controller{
Group root = new Group();
Scene s = new Scene(root, 300, 300, Color.BLACK);
public void buttonLayout() {
Button but = new Button("back to first");
but.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
Main main = new Main();
main.ps.setScene(main.s);
}
});
root.getChildren().add(but);
}
}
答案 0 :(得分:4)
重组您的应用程序,创建两个控制器而不是一个。所以每个场景都有一个控制器。在您的主应用程序中,只需调用第一个控制器来设置您的第一个场景。
以下是一个示例:
另一个不缓存场景或控制器的简化示例,不使用FXML并完全替换每个导航中场景的内容:
Main.java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class Main extends Application {
public void start(Stage stage) throws Exception {
Controller1 controller1 = new Controller1();
Scene scene = new Scene(
controller1.getContent(), 300, 300, Color.AQUA
);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller.java
import javafx.scene.Parent;
public interface Controller {
Parent getContent();
}
Controller1.java
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
public class Controller1 implements Controller {
private final StackPane root;
public Controller1() {
Button navToSecond = new Button("second");
navToSecond.setOnMouseClicked(event -> {
Controller2 controller2 = new Controller2();
navToSecond.getScene().setRoot(controller2.getContent());
});
root = new StackPane(navToSecond);
}
@Override
public Parent getContent() {
return root;
}
}
Controller2.java
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
public class Controller2 implements Controller {
private final StackPane root;
public Controller2() {
Button navToFirst = new Button("first");
navToFirst.setOnMouseClicked(event -> {
Controller1 controller1 = new Controller1();
navToFirst.getScene().setRoot(controller1.getContent());
});
root = new StackPane(navToFirst);
}
@Override
public Parent getContent() {
return root;
}
}