Totenfluch
Totenfluch

Reputation: 31

JavaFX resize string in Text object

I am trying to make a Text object of the width 100, and I want to display a String on the Text Object. And I want to change the font/size of the String when it is wider than 100, so the string fits perfectly inside of the object.

I searched a lot but couldn't find a handy solution.

Upvotes: 1

Views: 1549

Answers (1)

Kevin Reynolds
Kevin Reynolds

Reputation: 421

You could find out how wide a Text object is using a supplied String and setting the font. If the width is greater than 100, keep bumping the font size down until the text width is less than 100.

You can find the width as described here: How to calculate the pixel width of a String in JavaFX?

Sample Code

package application;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;


public class Main extends Application {

    Text text = new Text("Testing a really, really, long string");
    double size = 18;
    static final int MAX_WIDTH = 100;

    @Override
    public void start(Stage stage) {
        try {

            BorderPane border = new BorderPane();

            Scene scene = new Scene(border);
            stage.setWidth(200);
            stage.setHeight(100);

            Group group = new Group(text);

            setFontSize();

            System.out.println("Final font size: "+size);

            border.setCenter(group);

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

        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    private void setFontSize(){

        text.setFont(Font.font ("Arial", size));

        // java 7 => 
        //    text.snapshot(null, null);
        // java 8 =>
        text.applyCss();

        double width = text.getLayoutBounds().getWidth();

        if(width > MAX_WIDTH){
            size = size - 0.25;
            setFontSize();
        }
    }

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

Upvotes: 1

Related Questions