您需要將 psuedo-class添加到第二種樣式以允許聚焦環起作用,否則當您在第二種樣式類中重新指定按鈕的背景色時,您只需覆蓋它。
樣品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 and the JavaFX Scene Graph,雖然有在這個例子中的微妙之處,而您需要打開一個普通CSS規範理解的東西,如cascading order和specifity。
好吧,你幾乎得到了你的「接受答案」:-)。那麼能夠完成答案的東西就是關於如何在css中重寫的解釋。也許是因爲我是CSS的新手,但我找不到一個詳盡的解釋。 – AgostinoX
添加了一些指向JavaFX和一般css應用程序規則的鏈接。 – jewelsea
好的,但在那些文檔中,我已經找到了通用的CSS規則,但是如果我重寫它的「父」類,爲什麼會丟棄僞類呢?在你的「級聯順序」鏈接中,它只是說僞類被視爲類。 – AgostinoX