【问题标题】:Unable to close a stage in javafx through an Action event function无法通过 Action 事件函数关闭 javafx 中的阶段
【发布时间】:2017-11-27 14:27:35
【问题描述】:

我是 JavaFx 的初学者,我在简单地关闭阶段时遇到了问题。基本上我正在尝试创建一个作为确认框控制器的类。有一个“是”按钮和一个“否”按钮,但无论哪种方式,舞台都应该关闭并继续应用程序:

import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
// more imports...

public class ConfirmBoxController implements IView {

public javafx.scene.control.Button BTN_save;
public javafx.scene.control.Label label_Message;

private Stage stage;
private boolean answer;
private String title;
private String message;

public ConfirmBoxController(){
    this("Confirmation","Are you sure?");
}

public ConfirmBoxController(String title, String message){

    this.title = title;
    this.message = message;
    stage = new Stage();
}

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.setTitle(title);
        stage.setScene(scene);
        stage.showAndWait();

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

public void yes(ActionEvent actionEvent) {
    answer = true;
    stage.close();
}

public void no(ActionEvent actionEvent) {
    answer = false;
    stage.close();
}

注意:IView 是一个空界面。 基本上舞台出现了,我可以单击按钮,我知道这是正在注册的,因为当我单击按钮时会打印“是”和“否”功能。但是什么也没发生。

我确定我正在监督一些基本的事情,但我还没有找到如何正确地做到这一点。谢谢。

【问题讨论】:

    标签: java user-interface javafx-8 stage


    【解决方案1】:

    在控制器类中为您的按钮命名: @FXML 公共按钮 closeButton;

    并像这样添加:

    @FXML
    public void handleCloseButtonAction(ActionEvent event) {
        Stage stage = (Stage) closeButton.getScene().getWindow();
        stage.close();
    }
    

    在您的 FXML 中,您需要参考按钮名称和调用 onAction 的方法:

    <Button fx:id="closeButton" cancelButton="true" layoutX="350.0" layoutY="767.0" mnemonicParsing="false" onAction="#handleCloseButtonAction" prefWidth="100.0" text="Close" />
    

    【讨论】:

    • 谢谢,效果很好。不过,我真的不明白为什么。另外,你知道为什么函数“yes”和“no”不会改变“answer”的值吗?即确认总是返回“answer”的默认值。
    猜你喜欢
    • 2014-04-29
    • 2012-04-30
    • 2014-07-10
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 2014-04-07
    相关资源
    最近更新 更多