javafx中为tooltip设置显示时间
最近项目中用到了javafx中的tooltip提示框,因为是系统自带的所以用起来非常方便。但是使用后发现提示框的显示时间太短了,在百度上找了很长时间也没找到解决方案,于是决定自己研究一下源码,试试能不能找到解决方案。
在阅读源码的过程中看到了如下代码
private static TooltipBehavior BEHAVIOR = new TooltipBehavior(
new Duration(1000), new Duration(5000), new Duration(200), false);
通过名字和参数大概可以猜到这个变量就是用来控制显示时间的。为了验证猜想是否正确我便找到了TooltipBehavior这个类,它是Tooltip的一个内部类,它的构造方法如下图所示
文章图片
TooltipBehavior的构造方法
【javafx中为tooltip设置显示时间】图片只截取了方法头,从参数名字就能够看出来每个参数的作用。第一个参数用于指定从鼠标进入到提示框显示的时间,第二个参数就是我们苦苦寻找的提示框显示时间,第三个参数用于指定从鼠标移开到提示框消失的时间,第四个参数暂时不知道是什么,保持默认就行。
看完这些代码就可以动手修改显示时间了。大致方案是通过反射拿到TooltipBehavior的构造方法,利用构造方法创建对象,然后得到Tooltip的BEHAVIOR变量,最后将创建的TooltipBehavior对象赋值给BEHAVIOR变量。
具体实现代码如下:
public static void setTipTime(Tooltip tooltip,int time){
try {
Class tipClass = tooltip.getClass();
Field f = tipClass.getDeclaredField("BEHAVIOR");
f.setAccessible(true);
Class behavior = Class.forName("javafx.scene.control.Tooltip$TooltipBehavior");
Constructor constructor = behavior.getDeclaredConstructor(Duration.class, Duration.class, Duration.class, boolean.class);
constructor.setAccessible(true);
f.set(behavior, constructor.newInstance(new Duration(300), new Duration(time), new Duration(300), false));
} catch (Exception e) {
e.printStackTrace();
}
}
推荐阅读
- vue组件中为何data必须是一个函数()
- JavaFx介绍
- javaFX配置到myeclipse,并zzJavaFX和Java之间的互操作性
- JavaFX桌面应用-SpringBoot|JavaFX桌面应用-SpringBoot + JavaFX
- JavaFX 加载图片(使用Intellij IDEA)
- log4j打印抛出异常时堆栈内容
- 毕业设计写这个你就赢了《Netty|毕业设计写这个你就赢了《Netty + JavaFx 实战(仿桌面版微信聊天》)
- echarts中国地图+自定义tooltip样式+dispatchAction()方法实现联动
- javaFX的一些坑
- css做出丰富的Tooltips