【发布时间】:2015-11-24 09:13:21
【问题描述】:
我有一个名为 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?");
希望 display 方法返回一个变量,而不是 close 方法。我也不能只打电话 close ,因为那是行不通的。我能做些什么来帮助解决这个问题?非常感谢。
【问题讨论】:
-
这并不能回答你的问题,但是将
EventHandler接口传递给显示方法怎么样? -
* 实际上最好在调用
display方法之前在你的类中设置它。
标签: java user-interface javafx