按钮不使用JavaFx更改本地原始变量

时间:2017-06-24 11:07:24

标签: java javafx

我是JavaFx的新手,我正在尝试创建一个简单的确认框来确定用户是否真的要退出。它有一个返回布尔值的函数,表示用户是单击“是”还是“否”:

public class ConfirmBoxController implements IView {

    public javafx.scene.control.Button yes_BTN;
    public javafx.scene.control.Button no_BTN;

    private volatile boolean answer;

    // Constructors..//

    public boolean confirm(){
        try{
            stage = new Stage();
            FXMLLoader fxmlLoader = new FXMLLoader();
            Parent root = fxmlLoader.load(getClass().getResource("ConfirmBox.fxml").openStream());
            Scene scene = new Scene(root, 250, 140);
            stage.setScene(scene);
            stage.showAndWait();

            return answer;
        }
        catch(Exception E){
            E.printStackTrace();
            return true;
        }
    }

    public void yes() {
        this.answer = true;
        Stage stage = (Stage) yes_BTN.getScene().getWindow();
        stage.close();
    }

    public void no() {
        this.answer = false;
        Stage stage = (Stage) no_BTN.getScene().getWindow();
        stage.close();
    }
}

我试着让“回答”变得不稳定而不是,但它没有改变任何东西。

1 个答案:

答案 0 :(得分:0)

您可以在DialogAlert中使用javafx版本来实现此功能,这里有一个如何使用它们的教程:http://code.makery.ch/blog/javafx-dialogs-official/

这是您可能需要的:

Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Confirmation Dialog");
alert.setHeaderText("Look, a Confirmation Dialog");
alert.setContentText("Are you ok with this?");

Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK){
    // ... user chose OK
} else {
    // ... user chose CANCEL or closed the dialog
}

或者,如果您需要“是/否”提醒,则需要两个ButtonType s

Alert yesNoAlert = new Alert(Alert.AlertType.CONFIRMATION);
yesNoAlert.setTitle("Title");
yesNoAlert.setContentText("Content");
yesNoAlert.setHeaderText("Header");


ButtonType buttonYes = new ButtonType("Yes", ButtonBar.ButtonData.YES);
ButtonType buttonNo = new ButtonType("No" , ButtonBar.ButtonData.NO);

yesNoAlert.getButtonTypes().setAll(buttonYes,buttonNo);

Optional<ButtonType> result = yesNoAlert.showAndWait();
if (result.get() == buttonYes){
    // ...
} else  {
    // ...
}