gpt4 book ai didi

java - 如何从主应用程序的 init() 方法调用 JavaFX 应用程序预加载器实例中的方法

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

在 JavaFX 应用程序的 init() 方法中,我正在执行一些检查,其中之一是检查它是否可以使用 Http 响应代码连接到基于 Web 地址。该应用程序还有一个预加载器,可以在这些检查发生时运行。

根据响应代码,我希望它在预加载器应用程序的生命周期中显示警报窗口

我不确定使用当前的 javafx 预加载器类是否可以实现此目的,但是是否有任何解决方法可以实现此目的?

下面是我想要的 SSCCE

申请

public class MainApplicationLauncher extends Application implements Initializable{

...

public void init() throws Exception {

for (int i = 1; i <= COUNT_LIMIT; i++) {
double progress =(double) i/10;
System.out.println("progress: " + progress);

notifyPreloader(new ProgressNotification(progress));
Thread.sleep(500);
}

try {
URL url = new URL("https://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
System.out.println("Response code of the object is "+code);
if (code==200) {
System.out.println("Connected to the internet!");
}else if (code==503){
//call the handleConnectionWarning() in preloader
System.out.println("server down !");
}
} catch (UnknownHostException e) {
//call the handleConnectionWarning() in preloader
System.out.println("cannot connect to the internet!");
}

public static void main(String[] args) {
System.setProperty("javafx.preloader", MainPreloader.class.getCanonicalName());
Application.launch(MainApplicationLauncher.class, args);
}
}

预加载器

public class MyPreloader extends Preloader {

...

//Method that should be called from application method

public void handleConnectionWarning() {
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("Server is Offline");
alert.setHeaderText("Cannot connect to service");
alert.setContentText("Please check your connection");

alert.showAndWait();
}

}

有什么方法可以做到这一点吗?

最佳答案

预加载器

如果您想继续在启动画面中使用Preloader,那么您可以通过通知调用所需的方法。创建您自己的通知类:

// You can modify this class to carry information to the Preloader, such
// as a message indicating what kind of failure occurred.
public class ConnectionFailedNotification implements Preloader.PreloaderNotification {}

将其发送到您的预加载器:

notifyPreloader(new ConnectionFailedNotification());

并在所述预加载器中处理它:

@Override
public void handleApplicationNotification(PreloaderNotification info) {
if (info instanceof ConnectionFailedNotification) {
handleConnectionWarning();
}
// ...
}

无预加载器

当您通过 Java Web Start(即 Web 浏览器)部署应用程序时,Preloader 类更有意义,在使用代码之前必须下载代码。但 Java Web Start 不再受支持(尽管我认为可能有第三方维护至少类似的东西)。鉴于您的应用程序可能面向简单的桌面部署,使用 Preloader 可能会使事情变得不必要的复杂。相反,请考虑在初始化后简单地更新主要阶段的内容。

将您的 init() 内容移至 Task 实现中:

import java.io.IOException;
import javafx.concurrent.Task;

public class InitTask extends Task<Void> {

private static final int COUNT_LIMIT = 10;

private final boolean shouldSucceed;

public InitTask(boolean shouldSucceed) {
this.shouldSucceed = shouldSucceed;
}

@Override
protected Void call() throws Exception {
for (int i = 1; i <= COUNT_LIMIT; i++) {
updateProgress(i, COUNT_LIMIT);
Thread.sleep(500);
}

// could use a Boolean return type for this, but your real code seems
// more complicated than a simple "yes" / "no" response. If you do
// change the implementation to use a return value, note that you would
// then need to check that return value in the 'onSucceeded' handler
if (!shouldSucceed) {
throw new IOException("service unavailable"); // failure
}
return null; // success
}

}

然后在后台线程上启动该任务:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;;

public class App extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
var task = new InitTask(false); // change to 'true' to simulate success
task.setOnSucceeded(e -> primaryStage.getScene().setRoot(createMainScreen()));
task.setOnFailed(e -> {
var alert = new Alert(AlertType.WARNING);
alert.initOwner(primaryStage);
alert.setTitle("Server Offline");
alert.setHeaderText("Cannot connect to service");
alert.setContentText("Please check your connection");
alert.showAndWait();

Platform.exit();
});

// Also see the java.util.concurrent.Executor framework
var thread = new Thread(task, "init-thread");
thread.setDaemon(true);
thread.start();

var scene = new Scene(createSplashScreen(task), 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}

private StackPane createSplashScreen(InitTask task) {
var bar = new ProgressBar();
bar.progressProperty().bind(task.progressProperty());
return new StackPane(bar);
}

private StackPane createMainScreen() {
return new StackPane(new Label("Hello, World!"));
}
}

附注

您的Application子类不应实现Initialized。该子类代表整个应用程序,并且永远不应该用作 FXML Controller 。

关于java - 如何从主应用程序的 init() 方法调用 JavaFX 应用程序预加载器实例中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74986151/

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