您需要为: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 规范来理解诸如级联之类的东西顺序和特异性。