gpt4 book ai didi

JavaFX 防止在单击按钮时打开新阶段(窗口)

转载 作者:行者123 更新时间:2023-12-02 02:31:16 31 4
gpt4 key购买 nike

我有以下代码,它打开一个新的 JavaFX 阶段(我们称之为窗口)。

openAlertBox.setOnAction(e -> {
AlertBox alert = AlertBox.getInstance();
alert.display("AlertBox","Cool");
});

现在我想阻止用户每次点击时打开一个新窗口(因此,如果用户已经打开一个窗口,然后再次点击,则不会发生任何事情,因为窗口已经打开)

这是我的显示方法:

public void display(String title, String message) {
Stage window = new Stage();

window.initModality(Modality.NONE);
window.setTitle(title);
window.setMinWidth(250);

Label label = new Label();
label.setText(message);

VBox layout = new VBox(10);
layout.getChildren().addAll(label);
layout.setAlignment(Pos.CENTER);
//Display window and wait for it to be closed before returning
Scene scene = new Scene(layout);
window.setScene(scene);
window.showAndWait();
}

我怎样才能做到这一点?

最佳答案

创建一个窗口并重复使用它,而不是每次都创建一个新窗口。然后您可以检查它是否显示:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class ShowAndWaitNonModalTest extends Application {

private Stage alertWindow ;

@Override
public void start(Stage primaryStage) {
Button show = new Button("Show");

alertWindow = new Stage();

show.setOnAction(e -> {
if (! alertWindow.isShowing()) {
Button ok = new Button("OK");
Scene scene = new Scene(new StackPane(ok), 250, 250);
alertWindow.setScene(scene);
ok.setOnAction(evt -> alertWindow.hide());
alertWindow.showAndWait();
}
});


Scene scene = new Scene(new StackPane(show), 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {
launch(args);
}
}

或者您可以禁用显示它的任何控件:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class ShowAndWaitNonModalTest extends Application {

private Stage alertWindow ;

@Override
public void start(Stage primaryStage) {
Button show = new Button("Show");

alertWindow = new Stage();

show.setOnAction(e -> {
Button ok = new Button("OK");
Scene scene = new Scene(new StackPane(ok), 250, 250);
alertWindow.setScene(scene);
ok.setOnAction(evt -> alertWindow.hide());
alertWindow.showAndWait();
});

show.disableProperty().bind(alertWindow.showingProperty());

Scene scene = new Scene(new StackPane(show), 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {
launch(args);
}
}

关于JavaFX 防止在单击按钮时打开新阶段(窗口),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47043755/

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