0
有没有办法将使用CSS的JavaFX TextField的提示文本居中?我刚刚通过在提示文字前放置空格来实现它,但有时它仍然略微偏离。仅以文本框的提示文本为中心
[N ] http://i65.tinypic.com/i2kobl.png - >[ N ] http://i66.tinypic.com/2mxr0jk.png
有没有办法将使用CSS的JavaFX TextField的提示文本居中?我刚刚通过在提示文字前放置空格来实现它,但有时它仍然略微偏离。仅以文本框的提示文本为中心
[N ] http://i65.tinypic.com/i2kobl.png - >[ N ] http://i66.tinypic.com/2mxr0jk.png
提示文本显示在文本字段为空时,没有焦点。没有为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
伪类是没有设置,所以文本左对齐它是否被关注:
谢谢你的非常完整的答案。 – corpico