gpt4 book ai didi

java - 如何在不使用 .stopAndWait 方法的情况下使用 Javafx 中警报中的按钮?

转载 作者:行者123 更新时间:2023-11-30 05:56:58 24 4
gpt4 key购买 nike

我正在尝试在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 的替代方法。

最佳答案

您可以使用 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();
}
}

关于java - 如何在不使用 .stopAndWait 方法的情况下使用 Javafx 中警报中的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52997521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com