首页 > 解决方案 > 我用于确定适当字体大小的 while 循环太过分了……有时?

问题描述

我正在为学校做一个项目,该项目需要我读取文件并使用读取的数据制作条形图。我创建了一个类,它制作一个 JFrame 并绘制矩形以将框架划分为每个数据名称的部分(足球运动员姓名)和条形图(球员年龄)。我有一种方法旨在增加字体大小,直到最长(打印的)字符串占用分配空间的宽度,并返回该大小的字体以在paint方法中使用。

它在创建初始 JFrame 时起作用,但是当我调整它的大小时,它有时会将字体大小 1 增加到大,但并非总是如此。我很茫然。控制台输出(对我来说)显示我的 while 循环的条件没有得到满足,但字体大小仍然增加了......任何洞察力将不胜感激。谢谢!

private Font myFont(int allowedW, int allowedH, int numData) {
    // needs to check length of font and size of JFrame and set font (size)
    // accordingly
    String longest = "";
    int fontSize = 1;
    Font f = new Font("SansSerif", Font.BOLD, fontSize);
    for (BarData b : this.graphData) {
        if (getFontMetrics(f).stringWidth(b.getName()) > getFontMetrics(f)
                .stringWidth(longest)) {
            longest = b.getName();
        }
    }
    while ((getFontMetrics(f).stringWidth(longest) < allowedW)){
            //&& ((getFontMetrics(f).getHeight() * numData) < allowedH)) {
            f = new Font("SansSerif", Font.BOLD, fontSize);
        System.out.println(longest);
        System.out.println("length " + getFontMetrics(f).stringWidth(longest));
        System.out.println("allowed width " + allowedW);
        System.out.println(fontSize);
        fontSize++;
    }
    return f;
}

当我拖动以调整 jframe 的大小时,输出看起来像这样:

Demaryius Thomas
长度 150
允许宽度 158
17
Demaryius Thomas
长度 170
允许宽度 158
18

标签: javawhile-loopfontsjframefontmetrics

解决方案


像这样改变你的while循环,

while ((getFontMetrics(f).stringWidth(longest) < allowedW)){
            //&& ((getFontMetrics(f).getHeight() * numData) < allowedH)) {
        System.out.println(longest);
        System.out.println("length " + getFontMetrics(f).stringWidth(longest));
        System.out.println("allowed width " + allowedW);
        System.out.println(fontSize);
        fontSize++;
        f = new Font("SansSerif", Font.BOLD, fontSize);//your f is not updated after increasing fontSize, if you put it as first statement.
    }
return new Font("SansSerif", Font.BOLD, fontSize - 1);

推荐阅读