我想为按钮“确定”和“取消”提供一个方法,当用户单击这些按钮之一时将执行该方法:
如何使用我的代码执行此操作?
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Test");
alert.setHeaderText("This is a test.");
alert.setResizable(false);
alert.setContentText("Select okay or cancel this alert.");
alert.showAndWait();
根据我的理论,为其中一个按钮设置操作的代码如下所示:
alert.setActionForButtonOK(OkMethod());
最佳答案
alert#showAndWait
返回一个包含已按下按钮的可选值(如果没有按下任何按钮并且退出对话框,则返回 null
)。使用该结果来选择您要运行的操作。例如
Optional<ButtonType> result = alert.showAndWait();
if(!result.isPresent())
// alert is exited, no button has been pressed.
else if(result.get() == ButtonType.OK)
//oke button is pressed
else if(result.get() == ButtonType.CANCEL)
// cancel button is pressed
关于java - 如何为 JavaFX 警报按钮设置方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43031602/