关闭或隐藏带动画的舞台?

时间:2017-07-26 12:20:30

标签: javafx

好的,所以我正在构建这个小小的JavaFX应用程序以及其中的一个 让我感到困惑的是,虽然我的一些阶段会有那样的"放大 - 然后淡出"动画触发close()

特别关闭是此代码块中的最后一行代码:

@FXML
public void logout() throws SQLException {
    Stage stage = ((Stage) logout_button.getScene().getWindow());
    stage.close();
    Main.loginStage.show();
}

Main.loginStage.close();

这是方法的课程

public class ListController {

@FXML private ImageView profImg;
@FXML private Button logout_button;

@FXML private TableView<Child> table;
@FXML private TableColumn col_name;
@FXML private TableColumn col_picture;

//TO BE MOVED TO EXTERNAL CLASS
private static Database db;

@FXML
public void initialize() {
    db = new Database();
    try {
        initTable();
    } catch (SQLException e){
        System.out.println("loading  failed");
    }
    initAvatar();
    disableReorder();
}

private void initAvatar() {
    profImg.setClip(ImageUtils.getAvatarCircle());
    Image value = new Image("file:///" + GlobalInfo.getCurrProfImg().getAbsolutePath());
    profImg.setImage(value);
}

public void initTable() throws SQLException {
    db.init();

    table.setRowFactory(new Callback<TableView<Child>, TableRow<Child>>() {
        @Override
        public TableRow<Child> call(TableView<Child> param) {
            TableRow<Child> row = new TableRow<>();
            row.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    System.out.println(row.getItem().getId());
                }
            });
            return row;
        }});

    table.setItems(db.getChildren());
    col_picture.setCellValueFactory(new PropertyValueFactory<Child, File>("image"));
    col_picture.setCellFactory(new Callback<TableColumn<Child, File>, TableCell<Child, File>>() {
        @Override
        public TableCell call(TableColumn param) {
            return new TableCell<Child, File>() {
                ImageView imageView = new ImageView();
                Image childImage;

                @Override
                protected void updateItem(File item, boolean empty) {
                    if (item != null) {
                        childImage = new Image("file:///" + item.getAbsolutePath());

                        imageView.setImage(childImage);
                        imageView.setClip(ImageUtils.getAvatarCircle());
                        imageView.setFitHeight(65);
                        imageView.setFitWidth(65);
                        HBox hBox = new HBox(imageView);
                        hBox.setAlignment(Pos.CENTER);
                        setGraphic(hBox);
                    }
                }
            };
        }
    });



    col_name.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Child, String>, ObservableValue>() {
        @Override
        public ObservableValue call(TableColumn.CellDataFeatures<Child, String> param) {
            Child child = param.getValue();
            String firstName = child.getfName();
            String lastName = child.getlName();
            String nickname = child.getNickname();

            String placeholder = "PLACEHOLDER"; //Place holder for adding nickname if exists
            String complete = firstName + placeholder + lastName;

            //place nickname between first and last name if exists
            if (nickname.length() != 0){
                String nicknameString = " \"" + nickname + "\" ";
                complete =  complete.replace(placeholder, nicknameString);

            //if nickname does not exist
            } else {
                complete = complete.replace(placeholder, "");
            }
            return new SimpleStringProperty(complete);
        }
    });

    col_name.setCellFactory(new Callback<TableColumn<Child, String>, TableCell<Child, String>>() {
        @Override
        public TableCell call(TableColumn<Child, String> param) {
            return new TableCell<Child, String>() {
                @Override
                protected void updateItem(String item, boolean empty) {
                    setText(item);
                    setAlignment(Pos.CENTER);
                }
            };
        }
    });


}

private void disableReorder() {
    table.widthProperty().addListener((observable, oldValue, newValue) -> {
        TableHeaderRow row = ((TableHeaderRow) table.lookup("TableHeaderRow"));
        row.reorderingProperty().addListener((observable1, oldValue1, newValue1) -> row.setReordering(false));
    }); //Fuck you oracle
}


@FXML
public void logout() throws SQLException {
    Stage stage = ((Stage) logout_button.getScene().getWindow());
    stage.close();
    Main.loginStage.show();
}

@FXML
public void showSettings() throws IOException {
    Parent root = FXMLLoader.load(getClass().getResource("/fxml/settings.fxml"));
    SettingsStage stage = new SettingsStage();
    stage.setOnHidden((event) -> {
        SettingsStage settingsStage = ((SettingsStage) event.getSource());
        if (settingsStage.getChange()) {
            initialize();
        }
    });
    Scene scene = new Scene(root, 600, 400);
    stage.setScene(scene);
    stage.setTitle("Settings");
    stage.initModality(Modality.APPLICATION_MODAL);
    stage.showAndWait();
}

@FXML
public void showChildForm(ActionEvent actionEvent) throws IOException {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/childForm.fxml"));
    Parent root = loader.load();
    ChildFormController controller = loader.getController();
    controller.setListController(this);
    Scene scene = new Scene(root, 575, 675);
    scene.getStylesheets().add(getClass().getResource("/css/persistent-prompt.css").toExternalForm());

    Stage stage = new Stage();
    stage.setResizable(false);
    stage.setScene(scene);
    stage.setTitle("Add child");
    stage.initModality(Modality.APPLICATION_MODAL);

    stage.showAndWait();
}
}

然而,我有一些表格阶段没有显示这个&#34;动画&#34;在调用close()时,他们只是从窗口消失,我发现它很震撼。

这是运行以关闭其中一个故障阶段的代码,其各自的类进一步在下面:

@FXML
public void cancel(ActionEvent actionEvent) {
    Stage stage = ((Stage) submitBtn.getScene().getWindow());
    stage.close();
}
public class ChildFormController extends FormHelper {

@FXML
private ImageView childImage;
@FXML
private Label imageName;

@FXML
private PersistentPromptTextField firstNameInput;
@FXML
private PersistentPromptTextField lastNameInput;
@FXML
private PersistentPromptTextField nickNameInput;
@FXML
private PersistentPromptTextField birthPlaceInput;
@FXML
private PersistentPromptTextField referrerInput;

@FXML
private DatePicker birthDateInput;
@FXML
private DatePicker admissionDateInput;

@FXML
private Button submitBtn;

@FXML
private ComboBox childStatus;

//TWO SCOOPS TWO GENDERS TWO TERMS
@FXML
private ToggleGroup genderToggleGroup;

@FXML
private TextArea childDescInput;
@FXML
private Label warnEmptyLabel;

private FileInputStream slctdImgStrm;

private String pathRef;

private Parent nextParent;

private ChildParentsController childParentsController;

private ListController listController;

@FXML
public void initialize() throws FileNotFoundException {
    //Init gender choice buttons and scene ref
    //OMG MY PATRIARCHY
    genderToggleGroup.getToggles().get(0).setSelected(true);
    childStatus.getSelectionModel().selectFirst();

    //Init default image for child
    File defaultFile = new File("src\\main\\resources\\imgs\\default_avatar.png");
    updateChosenImage(defaultFile);

    //Init submit/next btn
    initNextBtn();

    childStatus.getSelectionModel().selectedIndexProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue.intValue() == 2) {
                initSubmitBtn();
            } else if (newValue.intValue() != 2 && oldValue.intValue() == 2) {
                initNextBtn();
            }
    });

    birthDateInput.valueProperty().addListener((observable, oldValue, newValue) -> {
        if (admissionDateInput.getValue() != null) {
            if (newValue.isAfter(admissionDateInput.getValue())) {
                birthDateInput.setValue(admissionDateInput.getValue());
            }
        }
    });

    admissionDateInput.valueProperty().addListener(((observable, oldValue, newValue) -> {
        if (birthDateInput.getValue() != null) {
            if (admissionDateInput.getValue().isBefore(birthDateInput.getValue())) {
                admissionDateInput.setValue(birthDateInput.getValue());
            }
        }
    }));
}

private void initNextBtn() {
    submitBtn.setText("Next");
    submitBtn.getStyleClass().remove("submit");
    submitBtn.getStyleClass().add("default");
    submitBtn.setOnAction(event -> initParentForm());
}

private void initParentForm() {
    if (formIsIncomplete())
        return;

    try {
        if (nextParent ==  null) {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/childParentsForm.fxml"));
            Parent root = loader.load();
            childParentsController = loader.getController();
            setNextParent(root);
        }
        submitBtn.getScene().setRoot(nextParent);
        childParentsController.setPrevRoot(submitBtn.getParent());
        childParentsController.setChildFormController(this);
    } catch (IOException e) {
        e.printStackTrace();
        DialogUtils.displayExceptionError(e, "Severe error!");
    }
}

private void initSubmitBtn() {
    submitBtn.setText("Submit");
    submitBtn.getStyleClass().remove("default");
    submitBtn.getStyleClass().add("submit");
    submitBtn.setOnAction(event -> submit(true));
}

@FXML
public void cancel(ActionEvent actionEvent) {
    Stage stage = ((Stage) submitBtn.getScene().getWindow());
    stage.close();
}


/**
 * Submits the child with all of its respecitve information
 * @param active if this controller's scene is active
 * @return id of child submitted, negative number if submission has failed
 */
public int submit(boolean active) {
    if (formIsIncomplete())
        return -1;

    //Fetch first part of user input
    String firstName = firstNameInput.getText();
    String lastName = lastNameInput.getText();
    String nickName = nickNameInput.getText();
    String place_of_birth = birthPlaceInput.getText();
    String childDesc = childDescInput.getText();
    String referrer = referrerInput.getText();

    int gender = genderToggleGroup.getToggles().indexOf(genderToggleGroup.getSelectedToggle());
    int status = childStatus.getSelectionModel().getSelectedIndex();

    //Get child's birthdate  and admission_date date
    LocalDate birthDate = birthDateInput.getValue();
    LocalDate admissionDate = admissionDateInput.getValue();

    //Fire up db helper and insert new child record
    Database db = new Database();

    //Retrieve record's ID for later use
    int id;


    try {
        //Add record for child and retrieve its id
        db.init();
        db.addNewChild(firstName, lastName, nickName, place_of_birth, birthDate, childDesc, gender, referrer, status, admissionDate);

        //Retrieve id for use in storing img
        id = db.getChildIDOf(firstName, lastName, nickName, place_of_birth, birthDate, childDesc, gender, referrer, status, admissionDate);
        if (id == -89) throw new SQLException();
        File strgReg = new File(pathRef.replace("id", String.valueOf(id)));

        //Store img file for child avatar
        if (!(strgReg.exists() && strgReg.isFile())) {
            strgReg.getParentFile().mkdirs();
            strgReg.createNewFile();
        }

        Files.copy(slctdImgStrm, Paths.get(strgReg.getPath()), StandardCopyOption.REPLACE_EXISTING);
        db.updateImageOf(id, strgReg.getPath(), table_children.name);
    } catch (SQLException e) {
        e.printStackTrace();
        DialogUtils.displayError("Error saving child data", "There was an error in saving all child data. Please try again!");
        return -1;
    } catch (IOException e) {
        e.printStackTrace();
        DialogUtils.displayError("Error saving image", "There was an error saving the image of the child. " +
                "All other data besides the image has been saved. Please attempt to add the child image in its own page.");
        return -1;
    }

    refreshList();
    if (active) {
        firstNameInput.getScene().getWindow().hide();
    }
    return id;
}

private boolean formIsIncomplete() {
    //Clear warning labels
    warnEmptyLabel.setStyle("-fx-text-fill: transparent");

    //Indicates that form is incomplete
    boolean incomplete = false;

    //Fetches textfield nodes from root
    try {
        List<Node> textFields = NodeUtils.getAllNodesOf(childImage.getParent(), new ArrayList<>(),
                "javafx.scene.control.TextInputControl");

        //Go mark each incomplete form
        for (Node n : textFields) {
            TextInputControl text = ((TextInputControl) n);

            String[] ids;

            if (text.getId() == null) {
                ids = new String[] {"birthDateWarning", "admissionDateWarning"};
            } else {
                ids = new String[] {text.getId().replace("Input", "Warning")};
            }

            //Manipulate warning label if current node is NOT nickname textfield
            if (!ids[0].contains("nick")) {
                for (int i = 0; i < ids.length; i++) {
                    Label warning = ((Label) childImage.getParent().lookup("#" + ids[i]));
                    if (text.getText().isEmpty()) {
                        warning.setStyle("-fx-text-fill: red");
                        incomplete = true;
                    } else {
                        warning.setStyle("-fx-text-fill: transparent ");
                    }
                }
            }
        }

        //Notify user that form is incomplete
        if (incomplete) warnEmptyLabel.setStyle("-fx-text-fill: red");

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        DialogUtils.displayExceptionError(e, "An error has occurred! Please contact the developer for assistance!");
    }
    return incomplete;
}

@FXML
public void changeChildImg(ActionEvent actionEvent) {
    FileChooser chooser = new FileChooser();
    File chosen = chooser.showOpenDialog(firstNameInput.getScene().getWindow());

    if (chosen == null) return;

    try {
        updateChosenImage(chosen);
    } catch (IOException e) {
        DialogUtils.displayError("File error", "There was an error selecting your chosen file, please try again");
        e.printStackTrace();
    }
}

private void updateChosenImage(File chosen) throws FileNotFoundException {
    slctdImgStrm = new FileInputStream(chosen);
    childImage.setImage(new Image(slctdImgStrm));
    imageName.setText(chosen.getName());
    pathRef = GlobalInfo.getChildrenImgDir() + "\\"+ chosen.getName();
    slctdImgStrm = new FileInputStream(chosen);
}

private void refreshList() {
    try {
        listController.initTable();
    } catch (SQLException e) {
        DialogUtils.displayError("Synchronization error!", "There was an error synchronizing the data of the new child!");
        e.printStackTrace();
    }
}

public void setNextParent(Parent nextParent) {
    this.nextParent = nextParent;
}

public void setListController(ListController listController) {
    this.listController = listController;
}

有没有人知道造成这个问题的原因是什么?任何关于SO的搜索都会产生关于淡入淡出阶段的问题,这不是我想要的。

0 个答案:

没有答案