最近項(xiàng)目中用到了javafx中的tooltip提示框,因?yàn)槭窍到y(tǒng)自帶的所以用起來非常方便。但是使用后發(fā)現(xiàn)提示框的顯示時間太短了,在百度上找了很長時間也沒找到解決方案,于是決定自己研究一下源碼,試試能不能找到解決方案。
在閱讀源碼的過程中看到了如下代碼
private static TooltipBehavior BEHAVIOR = new TooltipBehavior(
new Duration(1000), new Duration(5000), new Duration(200), false);
通過名字和參數(shù)大概可以猜到這個變量就是用來控制顯示時間的。為了驗(yàn)證猜想是否正確我便找到了TooltipBehavior這個類,它是Tooltip的一個內(nèi)部類,它的構(gòu)造方法如下圖所示

TooltipBehavior的構(gòu)造方法
圖片只截取了方法頭,從參數(shù)名字就能夠看出來每個參數(shù)的作用。第一個參數(shù)用于指定從鼠標(biāo)進(jìn)入到提示框顯示的時間,第二個參數(shù)就是我們苦苦尋找的提示框顯示時間,第三個參數(shù)用于指定從鼠標(biāo)移開到提示框消失的時間,第四個參數(shù)暫時不知道是什么,保持默認(rèn)就行。
看完這些代碼就可以動手修改顯示時間了。大致方案是通過反射拿到TooltipBehavior的構(gòu)造方法,利用構(gòu)造方法創(chuàng)建對象,然后得到Tooltip的BEHAVIOR變量,最后將創(chuàng)建的TooltipBehavior對象賦值給BEHAVIOR變量。
具體實(shí)現(xiàn)代碼如下:
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();
}
}