僅當文本字段爲空時,提示文本纔會顯示,因此我可以看到,執行此操作的最簡單方法是定義並「清空」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中嵌套選擇器。 –