Search code examples
textjavafxalignmenttextflow

Alignment of Text not working on TextFlow


I am new to javafx.

I am trying to build a messenger where the chatting panel show messages. I want to align the messages like my own messages are on left and other messages are on right.

To display the message i am using TextFlow where I add Text. But the alignment isnt working.

TextFLow tf=new TextFlow();
Text t1= new Text("Hi");
Text t2= new Text("Hello");
t1.setTextAlignment(TextAlignment.RIGHT);
t2.setTextAlignment(TextAlignment.LEFT);
tf.getChildren().addAll(t1,t2);

But the alignment not working. Both the text are on left. What should I do?


Solution

  • You can set the TextAlignement from the TextFlow but, i don't think we could have two alignment in the same container, however, you can use a tricky way to skirt this problem by using Labels & VBox:

    private VBox Chat(){
    
        VBox chat = new VBox();
        chat.setPrefSize(400, 400);
        chat.setStyle("-fx-background-color:#333333;");
    
        Label txt1 = new Label("Text1");
        txt1.setTextFill(Color.WHITE); 
        txt1.setPrefWidth(400); 
        txt1.setAlignment(Pos.CENTER_LEFT);
    
        Label txt2 = new Label("Text2");
        txt2.setTextFill(Color.WHITE); 
        txt2.setPrefWidth(400); 
        txt2.setAlignment(Pos.CENTER_RIGHT);  
    
        chat.getChildren().addAll(txt1,txt2);
    
        return chat;
    }
    

    Why Label ? This node work in the same way as the Text node but the advantage is that wet can resize the background.

    Why VBox ? is optional, even if i think TextFlow is better suited to textual nodes. It is also for the positioning, VBox is more suited for classified items from top to bottom chatting panel. Good luck !