在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();
}
}
有什么办法可以做到这一点吗?
1条答案
按热度按时间svmlkihl1#
预加载器
如果您想继续使用
Preloader
作为闪屏,那么您可以通过通知调用所需的方法。创建自己的通知类:发送到您的
Preloader
:并在上述
Preloader
中处理:无预加载器
通过Java Web Start部署应用程序时,
Preloader
类更有意义(例如,到Web浏览器),其中代码必须在使用之前下载。但不再支持Java Web Start(尽管我认为可能有第三方维护至少类似的东西)。假设您的应用程序可能针对简单的桌面部署,使用Preloader
可能会使事情变得不必要的复杂,而应考虑在初始化后简单地更新主阶段的内容。将您的
init()
内容移动到Task
实现中:然后在后台线程上启动该任务:
旁注
Application
子类不应实现Initializable
。该子类表示整个应用程序,并且绝不应用作FXML控制器。