我正在尝试用javafx创建一个游戏,当你赢了,弹出一个警告,告诉你你赢了,并且可以选择再次玩或关闭程序。问题是要在警告窗口中使用按钮,您必须使用alert.stopAndWait(),该方法不适用于时间轴。
有没有其他方法可以不使用这个方法来控制按钮,或者有没有更好的方法来编写代码?
感谢您的支持。
编辑:到目前为止,我的警报代码如下:
public static void alert(Alert.AlertType alertType, Window owner, String title, String message) {
Alert alert = new Alert(alertType);
alert.setHeaderText(null);
alert.setTitle(title);
alert.setContentText(message);
alert.initOwner(owner);
alert.show();
ButtonType buttonPlayAgain = new ButtonType("Play again");
alert.getButtonTypes().setAll(buttonPlayAgain);
alert.setOnHidden(evt -> Platform.exit());
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonPlayAgain){
// ... user chose Play Again"
System.out.println("play again");
} else
Platform.exit();
// if user clicks exit
问题是你不能使用有时间线的showAndWait。我正在尝试找到使用showAndWait的替代方案。
发布于 2018-10-26 04:47:30
您可以使用show()
方法,但您需要在关闭Alert
之后通过设置onCloseRequest()
处理程序来检索结果。
然后,您可以使用alert.getResult()
方法确定单击了哪个按钮。
下面是一个简单的演示程序:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
// Simple interface
VBox root = new VBox(5);
root.setPadding(new Insets(10));
root.setAlignment(Pos.CENTER);
// Button to show an alert
Button btnShowAlert = new Button("Show Alert!");
// Setup the button action
btnShowAlert.setOnAction(event -> {
// Create a simple Alert
Alert alert = new Alert(Alert.AlertType.NONE);
alert.setHeaderText(null);
alert.setTitle("Just a title");
alert.setContentText("A fun message");
// alert.initOwner(owner); // Remove for this sample
ButtonType buttonPlayAgain = new ButtonType("Play again");
alert.getButtonTypes().setAll(buttonPlayAgain);
// alert.setOnHidden(evt -> Platform.exit()); // Don't need this
// Listen for the Alert to close and get the result
alert.setOnCloseRequest(e -> {
// Get the result
ButtonType result = alert.getResult();
if (result != null && result == buttonPlayAgain) {
System.out.println("Play Again!");
} else {
System.out.println("Quit!");
}
});
alert.show();
});
root.getChildren().add(btnShowAlert);
// Show the Stage
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
https://stackoverflow.com/questions/52997521
复制相似问题