从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);
}
在上面的代码中,阴影也适用于提示文本,我想避免!
提示文本仅在文本字段为空时显示,因此,我看到的最简单的方法是定义和“清空” CSS PseudoClass。根据需要在文本上设置效果,然后在空文本字段中将文本的效果定义为null:
.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 ;
}
为了使伪类起作用,您需要在文本字段中使用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());
});
这是一个SSCCE(上面的CSS代码位于hint-text-styling.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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句