JavaFX FadeTransition与CSS -fx-opacity冲突

问题描述 投票:1回答:1

我正在使用一个按钮在JavaFX中构建一个自定义复合UI控件,如果将鼠标悬停在Control上的某个位置,它应该从0到0.1不透明度淡入。如果将鼠标悬停在按钮本身上,则不透明度应更改为1.0,这可以通过CSS轻松实现。

这里是FadeTransition:

// unfortunately, animations cannot be defined in CSS yet
FadeTransition fadeInButton =
    new FadeTransition(Duration.millis(300), settingsButton);
fadeInButton.setFromValue(0);
fadeInButton.setToValue(0.1);

这里是按钮的CSS:

.settings-button {
    -fx-background-image: url("settings_32_inactive.png");
    -fx-background-repeat: no-repeat;   
    -fx-background-position: center center;
    -fx-opacity: 0; /* button shall be initially invisible, will be faded in */
}

.settings-button:hover {
    -fx-background-image: url("settings_32.png");
    -fx-opacity: 1.0; /* why is this ignored if used together with animations? */
}

动画和CSS属性都可以单独使用。不幸的是,在组合中,动画似乎会覆盖CSS文件中的-fx-opacity属性。任何想法如何使动画和CSS属性一起工作?

css animation javafx-2 fadein conflict
1个回答
0
投票

没有办法让API调用css,请参阅下一主题:JavaFX: Cannot set font size programmatically after font being set by CSS

但你可以做下一招:

  • 如果悬停不透明,按钮的不透明度为0.1,按钮为1
  • 将按钮放入窗格并将此窗格设置为0到1

见下一个css:

/*Button*/
.b1 { -fx-opacity: 0.1; }
.b1:hover { -fx-opacity: 1.0; }
/*Pane*/
.p1 {
    -fx-border-color: red;
    -fx-opacity: 0;
}

和代码:

public class OpacityCss extends Application {

    private static final Duration DURATION = Duration.millis(300);

    @Override
    public void start(Stage primaryStage) {
        Pane pane = new Pane();
        pane.getStyleClass().add("p1");
        pane.setMinSize(100, 100);
        pane.setMaxSize(100, 100);

        final Button btn = new Button("Fading Button");
        btn.getStyleClass().add("b1");
        pane.getChildren().add(btn);

        final FadeTransition fade = new FadeTransition(DURATION, pane);
        fade.setAutoReverse(true);
        fade.setFromValue(0);
        fade.setToValue(1);

        pane.setOnMouseEntered(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent t) {
                fade.setCycleCount(1); // this way autoreverse wouldn't kick
                fade.playFromStart();
            }
        });

        pane.setOnMouseExited(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent t) {
                fade.setCycleCount(2); // starting from autoreverse
                fade.playFrom(DURATION);
            }
        });

        StackPane root = new StackPane();
        root.getChildren().addAll(pane);
        Scene scene = new Scene(root, 300, 250);
        scene.getStylesheets().add(getClass().getResource("/css/btn.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) { launch(); }
}
© www.soinside.com 2019 - 2024. All rights reserved.