【问题标题】:Center only the prompt text of textfield仅将 textfield 的提示文本居中
【发布时间】:2016-12-25 17:04:27
【问题描述】:

有没有办法使用 CSS 将 JavaFX TextField 的提示文本居中?我只是通过在提示文本前添加空格来临时处理它,但有时它仍然有点偏离。

[N ] http://i65.tinypic.com/i2kobl.png -> [ N ] http://i66.tinypic.com/2mxr0jk.png

【问题讨论】:

    标签: java javafx alignment textfield


    【解决方案1】:

    当文本字段为空且没有焦点时,提示文本会显示在文本字段中。 focused 有一个 CSS 伪类,但“空”没有预定义的 CSS 伪类,所以你需要创建一个:

    TextField textField = new TextField();
    textField.setPromptText("Enter something");
    
    PseudoClass empty = PseudoClass.getPseudoClass("empty");
    
    textField.pseudoClassStateChanged(empty, textField.getText().isEmpty());
    
    textField.textProperty().isEmpty().addListener((obs, wasEmpty, isNowEmpty) -> 
            textField.pseudoClassStateChanged(empty, isNowEmpty));
    

    现在您可以使用 CSS 如下方式在文本字段为空时将对齐方式设置为居中,在文本字段为空且具有焦点时设置为默认的左中对齐。

    SSCCE:

    import javafx.application.Application;
    import javafx.css.PseudoClass;
    import javafx.geometry.Insets;
    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 CenterPromptText extends Application {
    
        @Override
        public void start(Stage primaryStage) {
            TextField textField = new TextField();
            textField.setPromptText("Enter something");
    
            PseudoClass empty = PseudoClass.getPseudoClass("empty");
    
            textField.pseudoClassStateChanged(empty, textField.getText().isEmpty());
    
            textField.textProperty().isEmpty().addListener((obs, wasEmpty, isNowEmpty) -> 
                    textField.pseudoClassStateChanged(empty, isNowEmpty));
    
            VBox root = new VBox(5, textField, new Button("OK"));
            Scene scene = new Scene(root);
            scene.getStylesheets().add("center-prompt-text.css");
            primaryStage.setScene(scene);
            primaryStage.show();
    
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    center-prompt-text.css:

    .text-field:empty {
        -fx-alignment: center ;
    }
    .text-field:empty:focused {
        -fx-alignment: center-left ;
    }
    
    /*
     * settings on root just for cosmetic appearance;
     * 
     */
    
    .root {
        -fx-padding: 20 ;
        -fx-alignment: center ;
    }
    

    当你关注按钮时,提示文字出现并居中:

    如果您聚焦文本字段,它将恢复为左对齐(因此光标显示在左侧):

    如果您输入文本,empty 伪类未设置,因此无论是否聚焦文本都是左对齐的:

    【讨论】:

    • 感谢您提供非常完整的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 2020-03-11
    • 2014-02-21
    • 2020-03-27
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多