2016-08-18 33 views

回答

4

提示文本显示在文本字段为空时,没有焦点。没有为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 ; 
} 

当你专注于按钮,提示文本显示和居中:

enter image description here

如果你关注文本字段,它将恢复到左对齐(所以吨他游标显示在左侧):

enter image description here

,如果你输入文本时,empty伪类是没有设置,所以文本左对齐它是否被关注:

enter image description here

enter image description here

+0

谢谢你的非常完整的答案。 – corpico