java - 我用于确定适当字体大小的 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
解决方案
像这样改变你的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);
推荐阅读
- python - 如何显示字符出现的位置?
- python - 我正在尝试创建一个语音应用程序,但由于分段错误而出现错误
- python - 从另一个函数调用函数内定义的变量而不使用全局
- python - 在我的课堂上使用models.Model后,我得到'ImproperlyConfigured'错误Django
- java - pom文件配置打包外部/自定义jar文件在fat spring boot可执行jar文件中
- python - 偶尔调用 WMS 不会返回地图
- php - 消息:'未定义的偏移量' - 多个文件(图像)上传
- unity3d - Unity3d ProBuilder Spheres 导致高延迟?
- automated-tests - 在 Appium 中连接 XCAutomation 失败
- android - Android构建错误:无法获取'https://dl.google.com/dl/android/maven2/com/android/tools/build/aapt2/4.0.2-6197926/aapt2-4.0.2-6197926-osx。罐'