Skip to main content
 首页 » 编程设计

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

2023年09月11日33zfyouxi

我正在开发一个 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) { 
        Application.launch(args); 
    } 
 
    @Override 
    public void start(final Stage stage) { 
        VBox vbox = new VBox(); 
        Button b1 = new Button(); 
        b1.setId("the.button"); 
        b1.setText("BUTTON1"); 
 
        Button b2 = new Button(); 
        b2.setId("thebutton"); 
        b2.setText("BUTTON2"); 
 
        vbox.getChildren().addAll(b1, b2); 
        vbox.getStylesheets().add("stylesheet.css"); 
 
        final Scene scene = new Scene(vbox); 
 
        stage.setScene(scene); 
        stage.show(); 
    }     
} 

css文件是

#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

所以id没有限制,但是我不能写一个selector来选择它。我认为这是一个错误。

请您参考如下方法:

如果你解析你的 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 文档中列出的内容,您将遇到困难。