Skip to main content
 首页 » 编程设计

名称中带有点(句号)的 JavaFX css id 选择器


我正在开发一个 JavaFX 元素,其中节点 ID 必须是唯一的。这是通过使用“完整路径”名称命名它们来实现的,例如“myPane.button1”。当我尝试在 css 样式表中选择这些元素之一时,我不知道如何编写 id 选择器。这是一个示例应用程序,其中包含两个名为“the.button”和“thebutton”的按钮:

import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.layout.VBox; 
import javafx.stage.Stage; 
public class CssTest extends Application { 
    public static void main(final String[] args) { 
    public void start(final Stage stage) { 
        VBox vbox = new VBox(); 
        Button b1 = new Button(); 
        Button b2 = new Button(); 
        vbox.getChildren().addAll(b1, b2); 
        final Scene scene = new Scene(vbox); 


#the\.button { 
    -fx-graphic: url("Keyboard.png"); 
#thebutton { 
    -fx-graphic: url("Keyboard.png"); 

Escaping the dot should work ,但我无法让 JavaFX 匹配该元素。我在 JavaFX 文档中找不到对元素 id 的限制,包括 Node.setId 和 JavaFX css 引用,但如果不允许,更改名称将是一个很好的论据。

The JavaFX CSS reference says that

JavaFX Cascading Style Sheets (CSS) is based on the W3C CSS version 2.1 with some additions from current work on version 3. JavaFX CSS also has some extensions to CSS in support of specific JavaFX features.

我会得出结论,这意味着有效的 W3C CSS 文件也是有效的 JavaFX CSS 文件。然后定义id为

Each node in the scene graph has an id variable, a string. This is analogous to the id="..." attribute that can appear HTML elements. Supplying a string for a node's id variable causes style properties for this node to be looked up using that id. Styles for specific ids can be specified using the "#nodeid" selector syntax in a style sheet.

For HTML, the id attribute's naming convention is

Naming rules: Must contain at least one character Must not contain any space characters In HTML, all values are case-insensitive



如果你解析你的 CSS,你会看到:

    public static void main(String[] args) { 
         CSSParser cssParser =  new com.sun.javafx.css.parser.CSSParser(); 
         Stylesheet s = cssParser.parse("#the\\.button {\n" + 
"    -fx-graphic: url(\"Keyboard.png\");\n" + 
"}\n" + 
"\n" + 
"#thebutton {\n" + 
"    -fx-graphic: url(\"Keyboard.png\");\n" + 
         System.out.println(""); //add a breakpoint here 

id thebutton 只有一个规则,有两种方法可以理解为什么:


While the JavaFX CSS parser will parse valid CSS syntax, it is not a fully compliant CSS parser. One should not expect the parser to handle syntax not specified in this document.


这意味着如果您正在尝试属于 CSS 标准但未在 Oracle 文档中列出的内容,您将遇到困难。