在文本字段javaFX中提示文本

Oun*_*oni 3 css javafx textfield

从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);    
}
Run Code Online (Sandbox Code Playgroud)

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

Jam*_*s_D 5

提示文本仅在文本字段为空时显示,因此我能看到的最简单的方法是定义并“清空”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 ;
}
Run Code Online (Sandbox Code Playgroud)

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

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());
});
Run Code Online (Sandbox Code Playgroud)

这是一个 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);
    }
}
Run Code Online (Sandbox Code Playgroud)


H_B*_*aun 5

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

例:

.jfx-text-field {
-fx-prompt-text-fill: #989898;
}
Run Code Online (Sandbox Code Playgroud)

如果需要其他组件,请查找:JFoenix GitHub组件页面