Home > Software design >  How do I align certain lines of text to the right in JavaFX?
How do I align certain lines of text to the right in JavaFX?

Time:09-28

I'm using JavaFX to build a program wherein I need to display lines of text one after the other. Similarly to a messaging app such as WhatsApp, I need to align some lines of text to the right and others to the left, like this:

An example of a WhatsApp conversation

I first tried to use a TextArea, but I was only able to align all of the text towards one direction or the other. Additionally, it's a pain to add and remove text from a TextArea on the fly.

This led me to attempt to use a TextFlow instead, which makes use of Text nodes that I can control the individual attributes of, as well as add and remove as needed. While using the TextFlow however, I was still unable to align the nodes to the right of the Flow's area. I tried to use both the setStyle() and setTextAlignment() methods, to no avail.

TL,DR: How can I control the attributes of Text nodes within a JavaFX TextFlow such that some nodes are aligned to the right, while others are aligned to the left?

Many thanks

CodePudding user response:

There are several alternatives to achieve this. One approach would be to use a VBox for the layout, and a Label wrapped in an HBox for the text:

public class App extends Application {

    @Override
    public void start(Stage stage) {

        VBox pane = new VBox();
    
        pane.setPrefWidth(300);
        pane.setSpacing(10);
        pane.setAlignment(Pos.BOTTOM_CENTER);
        pane.setPadding(new Insets(20, 10, 20, 10));
    
        HBox text1 = createText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.", true);
        HBox text2 = createText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam vel quam erat.", false);
    
        pane.getChildren().setAll(text1, text2);

        StackPane root = new new StackPane(pane);
        root.setPrefSize(300, 300);

        Scene scene = new Scene(new StackPane(pane));

        stage.setScene(scene);
        stage.show();
    }

    private static HBox createText(String text, boolean right) {
        Label label = new Label(text);
        label.setWrapText(true);
        label.setMinWidth(200);
        label.setPrefWidth(200);
        label.setMaxWidth(200);
        label.setPadding(new Insets(5));
        label.setStyle("-fx-background-color: "   (right ? "#DCF8C6;" : "white;")   "-fx-background-radius: 10;");
        HBox pane = new HBox(label);
        pane.setAlignment(right ? Pos.CENTER_RIGHT : Pos.CENTER_LEFT);
        return pane;
    }

    public static void main(String[] args) {
        launch();
    }

}

Output:

Chat

  • Related