【问题标题】:How can I add a tooltip to a node that does not implement Control using FXML?如何向未使用 FXML 实现 Control 的节点添加工具提示?
【发布时间】:2023-03-15 12:45:01
【问题描述】:

Control 的JavaFX 子类中,有一个工具提示属性,这意味着可以使用FXML 以声明方式添加Tooltip

<CheckBox fx:id="someCheckBox" mnemonicParsing="false" text="Do It?">
    <tooltip>
        <Tooltip text="Whether or not to do it."/>
    </tooltip>
</CheckBox>

这是可能的,因为CheckBox 是 Control 的子类。

但是,我希望能够使用 FXML 向任何场景图节点添加工具提示(即,无需使用 Java 以编程方式添加工具提示)。

【问题讨论】:

    标签: javafx tooltip fxml


    【解决方案1】:

    Oracle 社区论坛上有一个archived discussion 建议将Node 包装在ScrollPane 内并在ScrollPane 上设置工具提示。虽然这不太理想,因为它向场景图中添加了一个不必要的节点,但更重要的是在所有场景中都不能正常工作。考虑尝试向TitledPane 的图形添加工具提示:

    <TitledPane text="My TitledPane" fx:id="someTitledPane" expanded="true" contentDisplay="RIGHT">
        <graphic>
            <ScrollPane fitToWidth="true" fitToHeight="true" style="-fx-background-color: rgba(255, 255, 255, 0);">
                <ImageView fitWidth="24.0" fitHeight="24.0" preserveRatio="true" pickOnBounds="true">
                <image>
                    <Image url="/images/questionMark.jpg" />
                </image>
                </ImageView>
            <tooltip>
                <Tooltip text="My tooltip."/>
            </tooltip>
            </ScrollPane>
        </graphic>
        <Label text="Hello!"/>
    </TitledPane>
    

    即使 ScrollPane 具有透明背景,问号图形后面仍然有一个可见的白框:

    有一种方法可以解决这个问题,那就是利用&lt;fx:script&gt; 的力量:

    <?language javascript?>
    
    <TitledPane text="My TitledPane" fx:id="someTitledPane" expanded="true" contentDisplay="RIGHT">
        <graphic>
            <ImageView fx:id="questionMarkImageView" fitWidth="24.0" fitHeight="24.0" preserveRatio="true" pickOnBounds="true">
            <image>
                <Image url="/images/questionMark.jpg" />
            </image>
            </ImageView>
            <fx:script>
                var tooltip = new javafx.scene.control.Tooltip('My tooltip');
                javafx.scene.control.Tooltip.install(questionMarkImageView, tooltip);
            </fx:script>
        </graphic>
        <Label text="Hello!"/>
    </TitledPane>
    

    请注意,ImageView 的fx:id 在脚本内部被引用(我没有在任何地方看到此功能的文档,只是通过实验找到了它 - 这实际上促使我发布此问答,希望其他人会发现它很有用)。结果如下:

    【讨论】:

      猜你喜欢
      • 2023-01-01
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      相关资源
      最近更新 更多