【问题标题】:How to affect other elements on hover in JavaFX Scene Builder?如何影响 JavaFX Scene Builder 中悬停时的其他元素?
【发布时间】:2021-02-24 07:35:05
【问题描述】:

我正在使用 SceneBuilder 在 JavaFX 中开发一个应用程序,我想添加一个 CSS 代码,当我将鼠标悬停在按钮上时将显示标签,我尝试了:

.label
{
-fx-text-fill: transparent;
}
.button:hover ~ .label 
{ 
-fx-text-fill: black; 
}

所有元素都在同一个容器中。 所以我的问题是如何使用按钮影响标签?

【问题讨论】:

  • 如果标签不是按钮的后代,您不能完全在 JavaFX CSS 中执行此操作;您需要在按钮的hoverProperty 上使用监听器。

标签: css javafx


【解决方案1】:

由于Label 不是button. 的后代,因此您将无法仅使用 JavaFX CSS 完成此操作

但是,您可以通过收听 hoverPropertyButton 并适当地设置 Label 的样式来更改 Label 的样式:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Sample extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        // Sample layout
        VBox root = new VBox(5);
        root.setAlignment(Pos.TOP_CENTER);
        root.setPadding(new Insets(5));

        // Create the Button and Label
        Button button = new Button("Hover Me!");
        Label label = new Label("You hovered like a pro!");

        // Add a listener to the button's hoverProperty. When it is triggered, we can update the
        // styleclass of the label.
        button.hoverProperty().addListener((observable, oldValue, newValue) -> {
            // If the current state is true, add the button-hovered styleclass
            if (newValue) {
                label.getStyleClass().add("button-hovered");
            } else {
                // Otherwise, we remove that class
                label.getStyleClass().remove("button-hovered");
            }
        });

        // Add the button and label to the layout
        root.getChildren().addAll(button, label);

        // Create the scene
        Scene scene = new Scene(root);

        // Apply CSS
        scene.getStylesheets().add("css/style.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

但是,在您的情况下,您可能会走错路,因为您只想隐藏Label,直到用户将鼠标悬停在Button 上。在这种情况下,将LabelvisibleProperty 绑定到ButtonhoverProperty 可能更简单。这样做只需要一行代码而不是使用监听器:

label.visibleProperty().bind(button.hoverProperty());

当然,如果你走这条路,你会想从你的 CSS 中删除 .label 选择器,因为它仍然会使文本透明。

【讨论】:

    猜你喜欢
    • 2011-05-29
    • 2019-01-27
    • 2023-03-21
    • 2015-04-20
    • 2023-03-14
    • 2013-08-01
    相关资源
    最近更新 更多