1

我创建了一个非常简单的 CSS 样式两个按钮。
第一个刚刚添加了一个填充。对第二个设置了 -fx-background-color,但该值取自 caspian.css,即它在设置之前应该具有的值。

.first-style { -fx-padding: 20 5 1 5; }

.second-style { -fx-background-color: -fx-shadow-highlight-color, -fx-outer-border, -fx-inner-border, -fx-body-color; }

此时我遇到了一个奇怪的行为:焦点装饰停止工作,第二个按钮在聚焦时没有蓝色边框。

在此处输入图像描述

发生了什么?

4

1 回答 1

2

您需要为:focused第二种样式添加一个伪类以允许对焦环工作,否则您只需在第二种样式类中重新指定按钮的背景颜色时覆盖它。

示例 CSS:

.root { -fx-background-color: cornsilk; -fx-padding: 10; }
.first-style { -fx-padding: 20 5 1 5; }
.second-style { -fx-background-color: -fx-shadow-highlight-color, -fx-outer-border, -fx-inner-border, -fx-body-color; }
.second-style:focused { -fx-background-color: -fx-focus-color, -fx-outer-border, -fx-inner-border, -fx-body-color; }

示例应用程序:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;

public class ButtonFocusCss extends Application {
  public static void main(String[] args) { launch(args); }
  @Override public void start(Stage stage) throws Exception {
    VBox layout = new VBox(15);
    Button b1 = new Button("B1");
    b1.getStyleClass().add("first-style");
    Button b2 = new Button("B2");
    b2.getStyleClass().add("second-style");
    layout.getChildren().addAll(b1, b2);
    layout.getStylesheets().add(getClass().getResource("button.css").toExternalForm());
    stage.setScene(new Scene(layout));

    stage.show();
  }
}

更新

老实说,我无法准确解释为什么 JavaFX CSS 覆盖机制会以这种方式工作,我在这里通过查看默认的JavaFX 2.2 caspian.css并根据它可能如何工作的预感得到了答案。

当前对 JavaFX CSS 应用规则的最佳解释在 CSS 参考指南部分CSS 和 JavaFX 场景图,尽管在此示例中存在一些细微之处,您需要求助于通用 CSS 规范来理解诸如级联之类的东西顺序特异性

于 2012-11-02T23:53:56.700 回答