我目前仍在使用Java 8,因此使用了一种解决方法,用于在JavaFX中设置工具提示的可见持续时间。虽然这可以让我控制工具提示保持打开状态的时间,但是当在用户界面的右下角显示工具提示,然后用户将鼠标悬停在工具提示上时,它会闪烁,直到鼠标退出为止。 我已经使用Java 11 / JavaFX 11尝试了以下代码,但是使用了:
'tooltip.setShowDuration(Duration.minutes(4)); //Some of my custom tooltips in the real application have a lot of detail and the user may need them open for a long time.'
我使用OnMouseExit卸载工具提示。这在Java 11中有效,并且不会闪烁,因为工具提示的位置更好,因此无法进行鼠标悬停(导致闪烁)。
不幸的是,我还没有搬到Java 11的地方。在下面的代码中,我在Java 8中看到的闪烁问题是否有解决方法。
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.util.Duration;
public class TooltipFlicker extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
updateTooltipBehavior(600, Duration.minutes(4).toMillis(), 200, true);
Tooltip tooltip=new Tooltip("Test the flicker bug!");
Button button= new Button("Flicker");
button.setOnMouseEntered(e->{
Tooltip.install(button, tooltip);
});
button.setOnMouseExited(e->{
Tooltip.uninstall(button, tooltip);
});
BorderPane borderPane = new BorderPane();
borderPane.setRight(button);
BorderPane bottomPane = new BorderPane();
bottomPane.setBottom(borderPane);
Scene scene = new Scene(bottomPane);
stage.setWidth(450);
stage.setHeight(500);
stage.setScene(scene);
stage.show();
}
/**Workaround I found on Stackoverflow to control tooltip behaviour pre-Java 9**/
private static void updateTooltipBehavior(double openDelay, double visibleDuration,
double closeDelay, boolean hideOnExit) {
try {
// Get the non public field "BEHAVIOR"
Field fieldBehavior = Tooltip.class.getDeclaredField("BEHAVIOR");
// Make the field accessible to be able to get and set its value
fieldBehavior.setAccessible(true);
// Get the value of the static field
Object objBehavior = fieldBehavior.get(null);
// Get the constructor of the private static inner class TooltipBehavior
Constructor<?> constructor = objBehavior.getClass().getDeclaredConstructor(
Duration.class, Duration.class, Duration.class, boolean.class
);
// Make the constructor accessible to be able to invoke it
constructor.setAccessible(true);
// Create a new instance of the private static inner class TooltipBehavior
Object tooltipBehavior = constructor.newInstance(
new Duration(openDelay), new Duration(visibleDuration),
new Duration(closeDelay), hideOnExit
);
// Set the new instance of TooltipBehavior
fieldBehavior.set(null, tooltipBehavior);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
要重新创建它,您需要将舞台最大化到全屏大小,然后将鼠标悬停在按钮右下角,按钮右下角的边缘上,然后将鼠标悬停在工具提示上。它将开始闪烁。
感谢您的帮助