如何使用 HandleButtonAction 和 if 语句使更多按钮工作

How to make more buttons work using HandleButtonAction and if-statements

我已经设法使用 if 和 else 语句让 2 个按钮工作。如果我添加另一个 if/else 语句,程序将不再有效。我如何添加更多语句,以便我的 GUI 中的其他按钮起作用?我还有大约 7 个按钮需要编码

 package finalgui;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;   
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;


public class FXMLDocumentController{

@FXML
private Button btnViewSPC;
@FXML
private Button btnBack;

@FXML
private void handleButtonAction(ActionEvent event) throws IOException{
Stage stage;
Parent root;
if(event.getSource()==btnViewSPC) {
    //get reference to the button's stage
    stage=(Stage) btnViewSPC.getScene().getWindow();
    //load up next scene
    root = FXMLLoader.load(getClass().getResource("addviewdel.fxml"));
}
else{
    stage=(Stage) btnBack.getScene().getWindow();
    root = FXMLLoader.load(getClass().getResource("FinalGUI.fxml"));
}
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}

}

当然你可以使用多个 if 语句来区分多个按钮

Object source = event.getSource();
if (source == button1) {
    ...
} else if (source == button2) {
     ...
} else if (source == button2) {
     ...
}
...
else {
     ...
}

但是我个人更喜欢使用 userData 属性:

将数据与 Button 相关联
@FXML
private void initialize() {
    btnViewSPC.setUserData("addviewdel.fxml");
    btnViewSPC.setUserData("FinalGUI.fxml");
    ...
}

@FXML
private void handleButtonAction(ActionEvent event) throws IOException {
    Node source = (Node) event.getSource();

    Stage stage = (Stage) source.getScene().getWindow();
    Parent root = FXMLLoader.load(getClass().getResource(source.getUserData().toString()));

    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
}

或者使用不同的方法来处理来自不同按钮的事件。您仍然可以在控制器中添加一个 "helper method" 以避免重复所有代码:

@FXML
private void handleButtonAction1(ActionEvent event) throws IOException {
    showStage(event, "addviewdel.fxml");
}

@FXML
private void handleButtonAction2(ActionEvent event) throws IOException {
    showStage(event, "FinalGUI.fxml");
}

...

private void showStage(ActionEvent event, String fxmlResource) throws IOException {
    Node source = (Node) event.getSource();

    Stage stage = (Stage) source.getScene().getWindow();
    Parent root = FXMLLoader.load(getClass().getResource(fxmlResource));

    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
}