我有一个称为GUI的类,用于管理我的应用程序。当用户想要在我的程序中删除他的帐户时,我希望弹出一个警告框并要求他确认或取消其操作,因此他不会意外删除他的帐户。
package application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.*;
/**
* An Alert Box for the GUI
* to display errors to the user.
*
*/
public class AlertBox
{
Stage window;
public boolean display(String title, String message)
{
boolean cancel = false;
window = new Stage(); // Create the stage.
window.initModality(Modality.APPLICATION_MODAL); // If window is up, make user handle it.
window.setTitle(title);
window.setMinHeight(350);
window.setMinWidth(250);
VBox root = new VBox(); // Root layout.
Label warning = new Label(message); // Message explaining what is wrong.
HBox buttonLayout = new HBox(); // The yes and cancel button.
Button yesButton = new Button("Yes"); // Yes button for the user.
Button noButton = new Button("No"); // No button for the user.
yesButton.setOnAction(e ->
{
cancel = false;
});
noButton.setOnAction(e ->
{
cancel = true;
});
buttonLayout.getChildren().addAll(yesButton, noButton);
root.getChildren().addAll(warning, buttonLayout);
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root);
window.setScene(scene);
window.show();
}
/**
* Closes the window and returns whether the user said yes or no.
* @param variable
* @return
*/
private boolean close(boolean variable)
{
window.close();
return variable;
}
}
我希望我的GUI类确切知道用户在AlertBox类中时发生了什么。用户单击了是还是否?因此,我考虑将显示方法设置为布尔值。问题出在这里,我的事件侦听器表达式无法返回任何值,因为它位于void类型的回调内部。然后我想:“哦,我将使close方法返回一个布尔值”。但是后来我想起了我调用的原始函数是:
AlertBox warning = new AlertBox;
boolean userWantsToDelete = warning.display("Warning!", "You are about to delete your account. Are you sure you would like to do this?");
希望显示方法返回变量,而不是关闭方法。我不能只打电话给close,因为那行不通。我该怎么做才能解决这个问题?非常感谢你。
您可以使用JavaFX Alerts轻松执行任务:
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Confirmation Dialog");
alert.setHeaderText("Warning !");
alert.setContentText("Are you sure you want to perform this action ?");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
// delete user
}
result.get()返回一个布尔值。因此,您可以检查用户是否单击ButtonType.OK
或ButtonType.CANCEL
通过在if条件内进行比较。
使用默认的“警报”,您有两个按钮,一个是“确定”按钮,另一个是“取消”。但是,如果您希望自定义警报,则可以向其中添加自己的按钮类型,如下所示:
ButtonType buttonTypeOne = new ButtonType("One");
ButtonType buttonTypeTwo = new ButtonType("Two");
ButtonType buttonTypeThree = new ButtonType("Three");
并将它们添加到警报中:
alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeTwo, buttonTypeThree);
因此,您可以检查用户按下了哪个按钮
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeOne){
// ... user chose "One"
} else if (result.get() == buttonTypeTwo) {
// ... user chose "Two"
} else{
// ... user chose "Three"
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句