Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
确定JavaFX字体的宽度和高度_Java_Javafx - Fatal编程技术网

确定JavaFX字体的宽度和高度

确定JavaFX字体的宽度和高度,java,javafx,Java,Javafx,我有一个对象,我需要字体的宽度和高度。我知道返回的是字体的高度,但在确定字体的宽度时,我不知所措 或者,能够确定字体支持的每个特定字符的宽度也是可以接受的解决方案 我的最佳猜测是,宽度是在使用该方法时指定的,但是文档没有指定size参数是表示字体的宽度还是高度 所有使用的字体都是单空间字体,如DejaVu Sans mono、GNU FreeMono和Lucida Sans Unicode。我遇到了同样的问题,似乎没有简单的方法。我的解决方案是使用正确的字体创建一个文本元素,并检查其大小: do

我有一个对象,我需要字体的宽度和高度。我知道返回的是字体的高度,但在确定字体的宽度时,我不知所措

或者,能够确定字体支持的每个特定字符的宽度也是可以接受的解决方案

我的最佳猜测是,宽度是在使用该方法时指定的,但是文档没有指定size参数是表示字体的宽度还是高度


所有使用的字体都是单空间字体,如DejaVu Sans mono、GNU FreeMono和Lucida Sans Unicode。

我遇到了同样的问题,似乎没有简单的方法。我的解决方案是使用正确的字体创建一个
文本
元素,并检查其大小:

double computeTextWidth(Font font, String text, double wrappingWidth) {
    Text helper = new Text();
    helper.setFont(font);
    helper.setText(text);
    // Note that the wrapping width needs to be set to zero before
    // getting the text's real preferred width.
    helper.setWrappingWidth(0);
    helper.setLineSpacing(0);
    double w = Math.min(helper.prefWidth(-1), wrappingWidth);
    helper.setWrappingWidth((int)Math.ceil(w));
    double textWidth = Math.ceil(helper.getLayoutBounds().getWidth());
    return textWidth;
}

如果我没记错的话,这里的技巧是将
prefWidth
设置为-1。请参见。

单个字符的宽度取决于要在其中使用字体的图形上下文。如果您想将字体用于文本字符串,这可能会很有帮助:另请参阅相关内容:Where is
Toolkit
imported from?我只得到了
java.awt.*
1.@sorbet给未来读者:
Toolkit
com.sun.javafx.tk.Toolkit
中。这是一个私有的内部API。
FontMetrics metrics = Toolkit.getToolkit().getFontLoader().getFontMetrics(font);
float charWidth = metrics.computeStringWidth("a");
float charHeight = metrics.getLineHeight();