2016-11-27 33 views
0

在我的程序中,文本字段从用户获取值并在窗口中显示值。但是我想在窗口右侧显示文本。如何更改javaFX窗口中的文本位置

我用setTextAlignment(TextAlignment.RIGHT)但它仍然显示在左边的文本(我不知道它是否是正确的方法来调用)。

我该如何解决它?

public class ChatBox extends Application{ 

    final ScrollPane sp = new ScrollPane(); 
    public void start(Stage stage){ 
    TextFlow textFlow = new TextFlow(); 
    textFlow.setPadding(new Insets(10)); 
    textFlow.setLineSpacing(10); 
    TextField textField = new TextField(); 
    textField.setPrefSize(50,30); 
    Button button = new Button("Send"); 
    button.setPrefSize(80,30); 
    VBox container = new VBox(); 
    VBox box = new VBox(); 
    box.getChildren().addAll(sp,textFlow); 
    container.setPadding(new Insets(10)); 
    container.getChildren().addAll(box, new HBox(textField, button)); 
    VBox.setVgrow(sp, Priority.ALWAYS); 
    VBox.setVgrow(textFlow, Priority.ALWAYS); 

textField.prefWidthProperty().bind(container.widthProperty().subtract(button.prefWidthProperty())); 

textField.setOnKeyPressed(e -> { 
    if(e.getCode() == KeyCode.ENTER) { 
     playSound(); 
     button.fire(); 
    } 
}); 
button.setOnAction(e -> { 
    Text text; 
    if(textFlow.getChildren().size()==0){ 
     text = new Text(textField.getText()); 
     text.setTextAlignment(TextAlignment.RIGHT); 
     String str = textField.getText(); 
     System.out.println(str); 
    } else { 
     text = new Text("\n" + textField.getText()); 
     text.setTextAlignment(TextAlignment.RIGHT); 
    } 
    textFlow.getChildren().add(text); 
    textField.clear(); 
    textField.requestFocus(); 
}); 
VBox vb = new VBox(); 
vb.getChildren().addAll(textFlow); 
sp.setVmax(440); 
sp.setPrefSize(400, 300); 
sp.setContent(vb); 
sp.vvalueProperty().bind((ObservableValue<? extends Number>) vb.heightProperty()); 
Scene scene = new Scene(container, 400, 300); 
stage.setScene(scene); 
stage.setTitle("jui"); 
stage.show(); 
} 
} 

回答

0

设置textAlignment属性个别孩子是不行的,因为TextFlow的定位总是使用。

您需要设置TextFlowtextAlignment属性:

textFlow.setTextAlignment(TextAlignment.RIGHT);