2016-08-18 1 views

답변

4

프롬프트 텍스트는 텍스트 필드에 표시됩니다. focused위한 CSS의 pseudoclass가 있지만 미리 정의 된 CSS의 pseudoclass는 "빈"에 대한이 없다, 그래서 당신은 하나를 만들어야합니다

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 :

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

당신이 초점을 맞출 경우 텍스트 필드가 있으면 왼쪽 맞춤으로 되돌아갑니다 (그래서 t

enter image description here

를하고 텍스트를 입력하면 empty pseudoclass이 설정되지 않은, 그래서 텍스트가 집중되는지 여부를 왼쪽 정렬 : 그는) 왼쪽에서 쇼 커서

enter image description here

enter image description here

+0

매우 완전한 답변에 감사드립니다. – corpico

관련 문제