如何在JavaFX中在不同类之间切换场景?

huangapple 未分类评论50阅读模式
英文:

How to switch scenes among different classes in javafx?

问题

以下是类MainMenu和supplierRegistration的代码部分。MainMenu类中只有一个名为"Add a new Supplier"的按钮,当点击此按钮时,希望能够切换到supplierRegistration界面。类似地,当在supplierRegistration界面点击返回按钮时,可以切换到MainMenu界面,但要求这两个界面不能同时打开。我正在努力实现这个功能。有人可以为我提供这方面的代码吗?非常感谢!

public class MainMenu extends Application {

    Scene mainMenuScene;
    Button addSupplierBtn;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("Main Menu");

        addSupplierBtn = new Button("Add a new Supplier");
        
        // 添加按钮点击事件
        addSupplierBtn.setOnAction(e -> {
            SupplierRegistration supplierRegistration = new SupplierRegistration();
            supplierRegistration.start(primaryStage);
        });

        StackPane layout = new StackPane();
        layout.getChildren().add(addSupplierBtn);

        mainMenuScene = new Scene(layout, 300, 250);
        primaryStage.setScene(mainMenuScene);
        primaryStage.show();
    }
}

// supplierRegistration类
public class SupplierRegistration extends Application {

    Stage window;
    Scene mainMenuScene;

    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        window.setTitle("Supplier Registration Form");
        GridPane gridPane = registrationPane();
        addUI(gridPane);

        Scene scene = new Scene(gridPane, 800, 500);
        window.setScene(scene);
        window.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    private GridPane registrationPane() {
        // ... (略去部分代码)
        return gridPane;
    }

    private void addUI(GridPane gridPane) {
        // ... (略去部分代码)
        backBtn.setOnAction(e -> window.setScene(mainMenuScene)); // 切换到MainMenu界面
    }

    private void alertBox(Alert.AlertType alertType, Window admin, String title, String message) {
        // ... (略去部分代码)
    }
}

以上是根据您提供的代码片段进行的翻译,希望对您有帮助。如果需要进一步解释或修改,请随时提问。

英文:

Below is the code for the classes: MainMenu and supplierRegistration. I have only one button in the MainMenu class called "Add a new Supplier", I want to add the functionality such that once this button is clicked I am able to move to the supplierRegistration screen and similarly when I click the back button while on the supplierRegistration screen I can switch to the MainMenu screen but the requirement is that both screens must not be open at the same time. I am struggling to implement this functionality. Can someone provide me with the code for this, I'll be very grateful, thank you!

public class MainMenu extends Application {

	Scene mainMenuScene;
	Button addSupplierBtn;

	public static void main(String[] args) {
		launch(args);
	}

	@Override
	public void start(Stage primaryStage) throws Exception {
		primaryStage.setTitle("Main Menu");

		addSupplierBtn = new Button("Add a new Supplier");

		// the layout.
		StackPane layout = new StackPane();
		layout.getChildren().add(addSupplierBtn);

		mainMenuScene = new Scene(layout, 300, 250);
		primaryStage.setScene(mainMenuScene);
		primaryStage.show();

	}
}

// now the supplierRegistration class.


public class supplierRegistration extends Application {

	Stage window;

	@Override
	public void start(Stage primaryStage) throws Exception {
		window = primaryStage;
		window.setTitle("Supplier Registration Form");
		GridPane gridPane = registrationPane();
		addUI(gridPane);

		Scene scene = new Scene(gridPane, 800, 500);
		window.setScene(scene);
		window.show();

	}

	public static void main(String[] args) {
		launch(args);

	}

	// now the layout.
	private GridPane registrationPane() {

		// declare and initliase a new GridPane layout.
		GridPane gridPane = new GridPane();

		// position the pane at the center.
		gridPane.setAlignment(Pos.CENTER);

		// set padding
		gridPane.setPadding(new Insets(40, 40, 40, 40));
		gridPane.setHgap(10);
		gridPane.setVgap(10);

		// add column constraints
		ColumnConstraints columnone = new ColumnConstraints(100, 100, Double.MAX_VALUE);
		columnone.setHalignment(HPos.RIGHT);

		ColumnConstraints columntwo = new ColumnConstraints(200, 200, Double.MAX_VALUE);
		columntwo.setHgrow(Priority.ALWAYS);
		gridPane.getColumnConstraints().addAll(columnone, columntwo);
		return gridPane;

	}

	private void addUI(GridPane gridPane) {
		// add header
		Label header = new Label("Register Supplier");
		header.setFont(Font.font("Arial Nova Light", FontWeight.BOLD, 22));
		gridPane.add(header, 0, 0, 3, 1);
		GridPane.setHalignment(header, HPos.CENTER);
		GridPane.setMargin(header, new Insets(20, 0, 20, 0));

		// full name label.
		Label fullName = new Label("Full Name");
		fullName.setMaxWidth(222); // 1240
		gridPane.add(fullName, 0, 1);

		// name textfield.
		TextField inputName = new TextField();
		inputName.setPrefHeight(28);
		inputName.setMaxWidth(222);
		gridPane.add(inputName, 1, 1);

		// addressline1 label.
		Label addressline1 = new Label("Address Line 1");
		addressline1.setMaxWidth(164);
		gridPane.add(addressline1, 0, 2);

		// addressline 1 textfield.
		TextField inputAddressLine1 = new TextField();
		inputAddressLine1.setPrefHeight(28);
		inputAddressLine1.setMaxWidth(222);
		gridPane.add(inputAddressLine1, 1, 2);

		// addressline 2 label.
		Label addressline2 = new Label("Address Line 2");
		addressline2.setMaxWidth(164);
		gridPane.add(addressline2, 0, 3);

		// addressline 2 textfield.
		TextField inputAddressLine2 = new TextField();
		inputAddressLine2.setPrefHeight(28);
		inputAddressLine2.setMaxWidth(222);
		gridPane.add(inputAddressLine2, 1, 3);

		// postcode label.
		Label postCode = new Label("Post Code");
		postCode.setMaxWidth(164);
		gridPane.add(postCode, 0, 4);

		// textfield for postcode
		TextField inputPostCode = new TextField();
		inputPostCode.setPrefHeight(28);
		inputPostCode.setMaxWidth(108);
		gridPane.add(inputPostCode, 1, 4);

		// email label.
		Label email = new Label("Email");
		email.setMaxWidth(164);
		gridPane.add(email, 0, 5);

		// textfield for email.
		TextField inputEmail = new TextField();
		inputEmail.setPrefHeight(28);
		inputEmail.setMaxWidth(222);
		gridPane.add(inputEmail, 1, 5);

		// label for cell phone number.
		Label mobilePhone = new Label("Mobile Phone");
		mobilePhone.setMaxWidth(164);
		gridPane.add(mobilePhone, 0, 6);

		// textfield for cell number.
		TextField mobileNumber = new TextField();
		mobileNumber.setPrefHeight(28);
		mobileNumber.setMaxWidth(222);
		gridPane.add(mobileNumber, 1, 6);

		// submit button.
		Button submitBtn = new Button("Submit");
		submitBtn.setId("submitBtn");
		submitBtn.setPrefHeight(36);
		submitBtn.setDefaultButton(true);
		submitBtn.setPrefWidth(82);
		gridPane.add(submitBtn, 0, 7, 2, 1);
		GridPane.setHalignment(submitBtn, HPos.LEFT);
		GridPane.setMargin(submitBtn, new Insets(30, 0, 30, 0));

		// back button which will take the user to the main menu.
		Button backBtn = new Button("Back");
		backBtn.setId("backBtn");
		backBtn.setPrefHeight(36);
		backBtn.setDefaultButton(true);
		backBtn.setPrefWidth(82);
		gridPane.add(backBtn, 0, 8, 2, 1);
		GridPane.setHalignment(backBtn, HPos.RIGHT);
		GridPane.setMargin(backBtn, new Insets(30, 0, 30, 0));

		submitBtn.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				if (inputEmail.getText().isEmpty() && mobileNumber.getText().isEmpty()) {
					alertBox(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Error",
							"Please provide either a valid email address or contact no");
					return;

				} else if (inputName.getText().isEmpty()) {
					alertBox(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Error",
							"Name Field cannot be empty!");
					return;

				} else if (inputAddressLine1.getText().isEmpty() && inputAddressLine2.getText().isEmpty()) {
					alertBox(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Error",
							"Address field cannot be empty!");
					return;

				} else if (postCode.getText().isEmpty()) {
					alertBox(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Error",
							"Post Code cannot be empty");

					return;

				}

				alertBox(Alert.AlertType.CONFIRMATION, gridPane.getScene().getWindow(), "Confirmation",
						"Supplier has been successfully registered!");

			}

		});
		// backBtn.setOnAction(e -> window.setScene(mainMenuScene));

	}

	private void alertBox(Alert.AlertType alertType, Window admin, String title, String message) {
		Alert alert = new Alert(alertType);
		alert.setTitle(title);
		alert.setHeaderText(null);
		alert.setContentText(message);
		alert.initOwner(admin);
		alert.show();

	}
}

答案1

得分: 0

程序应该只有一个类Application。移除SupplierRegistration类的extends Aplication,并将方法设置为public。

而在MainMenu中:

Button addSupplierBtn = new Button();
addSupplierBtn.setOnAction(event -> {
    SupplierRegistration regis = new SupplierRegistration();
    GridPane gridPane = regis.registrationPane();
    regis.addUI(gridPane);
    primaryStage.setTitle("Supplier Registration Form");
    primaryStage.setScene(new Scene(gridPane));
});

因此,另一种方法是将所有内容放入带有参数为window的构造函数中,并使用show方法:

public SupplierRegistration(Stage stage) {
    this.window = stage;
}

public void show() {
    GridPane gridPane = registrationPane();
    addUI(gridPane);
    window.setTitle("Supplier Registration Form");
    window.setScene(new Scene(gridPane));
}
英文:

A program should have only one class Application. Remove extends Aplication of SupplierRegistration class and set methods to public.

And in MainMenu:

Button addSupplierBtn = new Button();
addSupplierBtn.setOnAction(event -> {
        SupplierRegistration regis = new SupplierRegistration();
        GridPane gridPane = regis.registrationPane();
        regis.addUI(gridPane);
        primaryStage.setTitle("Supplier Registration Form");
        primaryStage.setScene(new Scene(gridPane));
    });

So, Another way is to put everything into the constructor with param is window and method show

public SupplierRegistration( Stage stage) {
    this.window= stage;
}
public void show(){
     GridPane gridPane =   registrationPane();
      addUI(gridPane);
      window.setTitle("Supplier Registration Form");
      window.setScene(new Scene(gridPane));
}

huangapple
  • 本文由 发表于 2020年5月4日 13:06:39
  • 转载请务必保留本文链接:https://java.coder-hub.com/61585515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定