javajavafx

In JavaFX, how to wrap text without breaking the words?


I use setMaxWidth to make TextFlow automatically wrap text. But if its width is small, it will break words like the following.

We only 
travele 
d 
togethe 
r for 
10 
years.

Is there a way to wrap the text without breaking the words?

I don't find any way to do this.


Solution

  • The needed feature is not a standard supported platform feature in JAVAFX. However, in order to accomplish this, you must first determine the maximum word width and specify it as the TextFlow's maxWidth property.

    A sample code to accomplish this is shown below:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.layout.StackPane;
    import javafx.scene.text.Text;
    import javafx.scene.text.TextFlow;
    import javafx.stage.Stage;
    
    public class TextWrapSample extends Application {
    
        @Override
        public void start(Stage primaryStage) {
            String content = "We only traveled together for 10 years";
            Text text = new Text(content);
            TextFlow textFlow = new TextFlow(text);
    
            //Set width of the textFlow
            double defaultMaxWidth = 5;
    
            double wordMaxWidth = calculateMaxWidthOfWord(content);
    
            // if defaultMaxWidth is small, increase it to prevent breaking longer words.
            textFlow.setMaxWidth(wordMaxWidth < defaultMaxWidth ? defaultMaxWidth : wordMaxWidth);
    
            StackPane root = new StackPane(textFlow);
            Scene scene = new Scene(root, 300, 200);
    
            primaryStage.setTitle("Text Wrap - Without Breaking Word");
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        private double calculateMaxWidthOfWord(String text) {
            double maxWidth = 0;
            String[] words = text.split(" ");
    
            for (String word : words) {
                Text tempText = new Text(word);
                double wordWidth = tempText.getLayoutBounds().getWidth();
    
                if (wordWidth > maxWidth) {
                    maxWidth = wordWidth;
                }
            }
    
            return maxWidth + 10; // Adding a small margin
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    Hope this will help.