我设法使用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();
}
}
答案 0 :(得分:2)
当然,您可以使用多个if
语句来命名多个按钮
Object source = event.getSource();
if (source == button1) {
...
} else if (source == button2) {
...
} else if (source == button2) {
...
}
...
else {
...
}
不过,我个人更喜欢使用Button
属性将数据与userData
相关联:
@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();
}
或者使用不同的方法来处理来自不同按钮的事件。您仍然可以添加"帮助方法"到控制器,以避免重复所有代码:
@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();
}