I have a Label in a GridPane in a TitledPane. I want it to downsize stepwise by 0.05em if it is overrun so the three dots (\"Long Labe...\") dont show up -> \"Long Label\" i
this function does the magic, basically calculates the compute size of the current label width the preferedWidth(could be change depending of the setting of the label) and if its bigger then reduce by 0.5 the font (also optional could be a custom value).
note: considere also set a condition to if the font is less than 0.5 to avoid that the font to not reach 0. Also could be converted with while instead of recursive function and also will be optimal, I will set both just in case
public Label ResizeTextIfOverrunRecursive(Label label, String text, double size) throws Exception {
FontLoader fontLoader = Toolkit.getToolkit().getFontLoader();
label.setFont(Font.font(size));
double font = label.getFont().getSize();
label.setStyle("-fx-font-size:" + (font) +"px;");
label.applyCss();
label.layout();
label.setText(text);
double prefWidth = label.getPrefWidth();
if (fontLoader.computeStringWidth(label.getText(), label.getFont()) > prefWidth){
return ResizeTextIfOverrunRecursive(label, text, size - 0.5);
} else return label;
}
public void ResizeTextIfOverrunItaration(Label label, String text, double size) throws Exception {
FontLoader fontLoader = Toolkit.getToolkit().getFontLoader();
label.setFont(Font.font(size));
double font = label.getFont().getSize();
label.setStyle("-fx-font-size:" + (font) +"px;");
label.applyCss();
label.layout();
double prefWidth = label.getPrefWidth();
while (fontLoader.computeStringWidth(label.getText(), label.getFont()) > prefWidth){
font -= 0.5;
label.setStyle("-fx-font-size:" + (font) +"px;");
label.applyCss();
label.layout();
}
label.setText(text);
}