如何使文本字体缩小并匹配JTextArea的高度?

3

我有一个JTextArea接收文本,但问题是当文本过长时,它无法适应并出现滚动条。我想要的是自动缩小字体大小以匹配JTextArea的高度。

目前情况如下图所示

寻找java.awt.FontMetrics类,它可以完成这项工作。 - Akila
“但问题是当文本太长时,它无法适应并出现滚动条。” 这不是问题,而是一种特性。 - Andrew Thompson
1个回答

1
使用以下方法,(根据您的要求更新最大和最小尺寸)
public static int getMatchingFontSize(JComponent comp, String string) {
    int minSize = 10;
    int maxSize = 60;
    Dimension size = comp.getSize();

    if (comp == null || comp.getFont() == null || string.isEmpty()) {
        return -1;
    }
    //Init variables
    int width = size.width;
    int height = size.height;

    Font font = comp.getFont();
    int curSize = font.getSize();
    FontMetrics fm = comp.getFontMetrics(new Font(font.getName(), font.getStyle(), maxSize));
    while (fm.stringWidth(string) + 4 > width || fm.getHeight() > height) {
        maxSize--;
        fm = comp.getFontMetrics(new Font(font.getName(), font.getStyle(), maxSize));
        curSize = maxSize;
    }
    while (fm.stringWidth(string) + 4 < width || fm.getHeight() < height) {
        minSize++;
        fm = comp.getFontMetrics(new Font(font.getName(), font.getStyle(), minSize));
        curSize = minSize;
    }
    if (curSize < minSize) {
        curSize = minSize;
    }
    if (curSize > maxSize) {
        curSize = maxSize;
    }
    return curSize;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接