文本字段 javaFX 中的提示文本

prompt text in text field javaFX

来自 JavaFX CSS 我只想对提示文本应用效果而不影响 TextField 中的文本,但不知道如何访问该项目。我只能使用 -fx-prompt-text-fill 更改颜色。当我对文本应用效果时,提示文本也会受到影响,为什么?

.text-field {
    -fx-prompt-text-fill: gray;
}
.text-field > .text {
        -fx-effect: dropshadow( two-pass-box , blue , .5, 10 , 1 , 1);    
}

在上面的代码中,我还想避免将阴影应用于提示文本!!

提示文本仅在文本字段为空时显示,因此我认为最简单的方法是定义 "empty" CSS PseudoClass。根据需要设置文本效果,然后将空文本字段中的文本效果定义为空:

.text-field {
    -fx-prompt-text-fill: gray;
}

.text-field .text {
    -fx-effect: dropshadow( two-pass-box , blue , .5, 10 , 1 , 1);    
}

.text-field:empty .text {
    -fx-effect: null ;
}

要使伪类工作,您需要在文本字段中使用文本 属性 注册一个侦听器并更新它:

TextField textField = new TextField();
textField.setPromptText("Enter text");

PseudoClass empty = PseudoClass.getPseudoClass("empty");
textField.pseudoClassStateChanged(empty, true);
textField.textProperty().addListener((obs, oldText, newText) -> {
    textField.pseudoClassStateChanged(empty, newText.isEmpty());
});

这是一个 SSCCE(上面 prompt-text-styling.css 中的 CSS 代码):

import javafx.application.Application;
import javafx.css.PseudoClass;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class TextFieldPromptStylingTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        TextField textField = new TextField();
        textField.setPromptText("Enter text");

        PseudoClass empty = PseudoClass.getPseudoClass("empty");
        textField.pseudoClassStateChanged(empty, true);
        textField.textProperty().addListener((obs, oldText, newText) -> {
            textField.pseudoClassStateChanged(empty, newText.isEmpty());
        });

        Button okButton = new Button("OK");
        VBox root = new VBox(10, textField, okButton);
        root.setAlignment(Pos.CENTER);
        root.setPadding(new Insets(24));

        Scene scene = new Scene(root);
        scene.getStylesheets().add("prompt-text-styling.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

如果您使用 JFoenix,则可以使用样式表设置提示文本的样式。 CSS-Class 是 .jfx-text-field 而 属性 -fx-prompt-text-fill.

示例:

.jfx-text-field {
-fx-prompt-text-fill: #989898;
}

如果您需要其他组件,请查找:JFoenix GitHub components page