简体   繁体   中英

How to change text position in window in javaFX

In my program a text field takes value from the user and shows the value in the window. But i want show the texts in the right of the window.

I used setTextAlignment(TextAlignment.RIGHT) but it still shows texts in the left(I'm not sure whether it is the right method to call).

How can i solve it?

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

Setting the textAlignment property for individual children does not work, since the alignment of the TextFlow is always used.

You need to set the textAlignment property of the TextFlow :

textFlow.setTextAlignment(TextAlignment.RIGHT);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM