JavaFX 第三篇 HostServices和Platform
1、HostServices类
介绍这个类主要是使用里面的一个方法
返回类型 | 方法 | 说明 |
void | showDocument(java.lang.String uri) | 使用默认浏览器打开一个url地址 |
/*** @description: 程序打开3秒后,打开百度* @author: HK* @since: 2025/4/24 16:40*/
public class Demo1 extends Application {public static void main(String[] args) {launch();}@Overridepublic void start(Stage primaryStage) throws Exception {// 设置窗体标题primaryStage.setTitle("测试HostServices");// 设置窗体大小primaryStage.setWidth(400);primaryStage.setHeight(400);// 窗体显示primaryStage.show();Thread.sleep(3000);// 获取HostServicesHostServices hostServices = getHostServices();// 打开网页hostServices.showDocument("www.baidu.com");}
}
2、Platform类
(1)runLater方法
runLater(java.lang.Runnable runnable):在JavaFX Application线程空闲时运行,他不会单独开启一个线程,他和application是同一个线程,可以做一些简单的页面刷新等操作。
/*** @description: Platform类方法介绍* @author: HK* @since: 2025/4/24 16:40*/
public class Demo2 extends Application {public static void main(String[] args) {launch();}@Overridepublic void start(Stage primaryStage) throws Exception {Platform.runLater(() -> {System.out.println("Platform中run方法的线程名称:" + Thread.currentThread().getName());});System.out.println("Application中start方法的线程名称:" + Thread.currentThread().getName());}
}
(2)setImplicitExit方法
setImplicitExit(boolean implicitExit):设置Fx窗体关闭后,后台程序时候也进行关闭
true:表示窗体关闭,程序也会关闭
false:表示窗体关闭,程序不会关闭
/*** @description: Platform类方法介绍* @author: HK* @since: 2025/4/24 16:40*/
public class Demo3 extends Application {public static void main(String[] args) {launch();}@Overridepublic void start(Stage primaryStage) throws Exception {Platform.setImplicitExit(false);// 设置窗体标题primaryStage.setTitle("测试setImplicitExit方法");// 设置窗体大小primaryStage.setWidth(400);primaryStage.setHeight(400);// 窗体显示primaryStage.show();}
}
(3)exit方法
exit():退出程序
/*** @description: Platform类方法介绍* @author: HK* @since: 2025/4/24 16:40*/
public class Demo3 extends Application {public static void main(String[] args) {launch();}@Overridepublic void start(Stage primaryStage) throws Exception {// 设置窗体标题primaryStage.setTitle("测试setImplicitExit方法");// 设置窗体大小primaryStage.setWidth(400);primaryStage.setHeight(400);// 窗体显示primaryStage.show();// 3秒后程序自动关闭Thread.sleep(3000);Platform.exit();}
}
(4)isSupported方法
isSupported(ConditionalFeature feature):查询平台是否支持指定的条件特性
ConditionalFeature.SCENE3D:3D效果
public class Demo3 extends Application {public static void main(String[] args) {launch();}@Overridepublic void start(Stage primaryStage) throws Exception {// 设置窗体标题primaryStage.setTitle("测试setImplicitExit方法");// 设置窗体大小primaryStage.setWidth(400);primaryStage.setHeight(400);// 窗体显示primaryStage.show();// 查看平台是否支持3DSystem.out.println(Platform.isSupported(ConditionalFeature.SCENE3D));}
}
常用的方法runLater和exit