001package conexp.fx.gui.util; 002 003/* 004 * #%L 005 * Concept Explorer FX 006 * %% 007 * Copyright (C) 2010 - 2023 Francesco Kriegel 008 * %% 009 * This program is free software: you can redistribute it and/or modify 010 * it under the terms of the GNU General Public License as 011 * published by the Free Software Foundation, either version 3 of the 012 * License, or (at your option) any later version. 013 * 014 * This program is distributed in the hope that it will be useful, 015 * but WITHOUT ANY WARRANTY; without even the implied warranty of 016 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 017 * GNU General Public License for more details. 018 * 019 * You should have received a copy of the GNU General Public 020 * License along with this program. If not, see 021 * <http://www.gnu.org/licenses/gpl-3.0.html>. 022 * #L% 023 */ 024 025import javafx.scene.Scene; 026import javafx.scene.control.LabelBuilder; 027import javafx.scene.text.Text; 028import javafx.scene.text.TextBuilder; 029import javafx.stage.Stage; 030import javafx.stage.StageBuilder; 031import javafx.stage.StageStyle; 032 033@SuppressWarnings("deprecation") 034public final class TextWidthCalculator { 035 036 private static final Text text = TextBuilder.create().opacity(0).build(); 037 private static final Stage stage = StageBuilder 038 .create() 039 .opacity(0) 040 .style(StageStyle.UTILITY) 041 .scene(new Scene(LabelBuilder.create().graphic(text).build())) 042 .build(); 043 044 public static final double getMaximalTextWidth(final int textSize, final Iterable<String> strings) { 045 return getMaximalTextWidth("-fx-font-size: " + textSize + ";", strings); 046 } 047 048 public static final double getMaximalTextWidth(final String style, final Iterable<String> strings) { 049 text.setStyle(style); 050 double maxWidth = 0; 051 for (final String string : strings) 052 maxWidth = Math.max(maxWidth, getTextWidth(string)); 053 return maxWidth; 054 } 055 056 public static synchronized final double getTextWidth(final String string) { 057 text.setText(string); 058 stage.show(); 059 final double width = text.getLayoutBounds().getWidth(); 060 stage.hide(); 061 return width; 062 } 063 064}