JavaFX:不使用FXML返回主页面
我正在自学JavaFx,还没有达到FXML的水平。我被一个应用程序卡住了,我计划在用户在第二个场景中输入他们的凭据后让它返回到应用程序的主场景。我设法把第二个场景从主场景调出,但我无法从第二个场景调到主场景。我尝试使用getter获取主场景和窗格,但没有成功。你们能教给我正确的方法吗
先谢谢你
public class Landing extends Application {
BorderPane bp;
Scene scene;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Welcome to our Telco!");
bp = new BorderPane();
VBox vbox = new VBox();
Button login = new Button("Login");
login.setMinWidth(100);
Button acc = new Button("Account Information");
acc.setMinWidth(100);
vbox.getChildren().addAll(acc);
bp.setCenter(vbox);
acc.setOnAction(e ->{
AccountInfo account = new AccountInfo();
primaryStage.setTitle("Account Information"); // Set the stage title
primaryStage.getScene().setRoot(account.getbp());; // Place the scene in the stage
});
scene = new Scene(bp, 750, 550);
primaryStage.setScene(scene);
primaryStage.show();
}
public Pane getbp() {
return bp;
}
public Scene getSc(){
return scene;
}
获取主场景的按钮
public class AccountInfo {
BorderPane pane;
Landing main = new Landing();
Scene scene;
AccountInfo() {
Button c = (new Button("Back"));
c.setStyle("-fx-background-color: pink");
c.setOnAction((ActionEvent e) -> {
main.getbp();
main.getSc();
});
public Pane getbp() {
return pane;
}
}
# 1 楼答案
Landing
不是一个场景,而是一个Application
。到目前为止,整个应用程序中只有一个场景。在同一JavaFX应用程序生命周期内,任何Application
类都不能尝试实例化(并随后运行)多个实例。当你在AccountInfo
课上做Landing main = new Landing();
时,你正在危险地朝这个方向走从Javadoc到
Application.launch
:你需要的是登录的第一个场景(即输入凭证)。登录成功后,您将创建一个新的场景对象,并用下一个“视图”填充该场景,然后将该新场景设置为舞台