我用于确定适当字体大小的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 大小时,输出看起来像这样:

德马里尤斯·托马斯 长度 150 允许宽度 15817
德马里尤斯·托马斯

长度 170

允许宽度 158 18

像这样更改你的 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);

最新更新