我有一个叫做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的回调内部。然后我想,“哦,我只需使关闭方法返回一个布尔值”。但是,我记得我调用的原始函数是:
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方法,我也不能直接调用close方法,因为那样行不通。有什么办法可以解决这个问题吗?非常感谢。
EventHandler
接口传递给display
方法怎么样? - Tomasz Mularczyk