2016-08-18 6 views
0

CSSを使用する可能性があるJavaFX TextFieldのプロンプトテキストを中央に配置する方法はありますか?私はちょうどプロンプトのテキストの前にスペースを入れてアドホックにしていますが、時にはそれはまだ少しです。テキストフィールドのプロンプトテキストのみを中心に

[N ] http://i65.tinypic.com/i2kobl.png - それは空で、フォーカスがないとき>[ N ] http://i66.tinypic.com/2mxr0jk.png

答えて

4

プロンプトテキストは、テキストフィールドに示されています。 focusedためのCSS疑似クラスがありますが、あなたは1を作成する必要があるので、「空」のための事前に定義された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を使用することができますフィールドが空で、デフォルトのcenter-left(テキストフィールドが空でフォーカスされている場合)に移動します。

SSCCE:center-prompt-text.css

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); 
    } 
} 

.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

あなたが集中した場合テキストフィールドは、左揃えに戻ります(したがって、t彼は)左にショーをカーソル:

enter image description here

、あなたがテキストを入力すると、empty擬似クラスは設定されていないので、テキストは左揃えされ、それがフォーカスされているかどうか:

enter image description here

enter image description here

+0

非常に完全な回答ありがとうございます。 – corpico

関連する問題