仅当文本字段为空时,提示文本才会显示,因此我可以看到,执行此操作的最简单方法是定义并“清空”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(与CSS代码上面的提示文字 - 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);
}
}
你能解决您的CSS? '.textField'不是'TextField'的CSS类,你可以在CSS中嵌套选择器。 –