最大化字体大小,同时将文本保留在JTextField中 [英] Maximize font size while keeping text within JTextField
问题描述
我有一个JTextField,其大小可能取决于分辨率.JTextField将包含3个字母的字符串.
I have a JTextField which may vary in size depending on resolution. The JTextField will hold a 3 letter string.
我想设置JTextField的字体大小以最大化字体大小,同时仍将文本FIT完美地放在JTextField内部.
I want to set the font size of the JTextField in such a way to MAXIMIZE the font size while still having the text FIT inside of the JTextField perfectly.
有没有算法可以做到这一点?
Is there an algorithm to do this?
推荐答案
我使用了Martijn的答案以及以下答案:
I have used Martijn's answer, along with the following answers:
...以便为我的问题写出完整的答案.来了感谢所有贡献者.
...in order to write a full answer to my question. Here it goes. Thanks to all who contributed.
您将需要导入以下内容:
You will need to import the following:
import javax.swing.JTextField;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.awt.FontMetrics;
import java.lang.Math;
.................................
.................................
public int getFontSize(JTextField text, int columnsToHold){
//Create a sample test String (we will it later in our calculations)
String testString = "";
for(int i = 0; i<columnsToHold; i++){
testString = testString + "5";
}
//size will hold the optimal Vertical point size for the font
Boolean up = null;
int size = text.getHeight();
Font font;
while (true) {
font = new Font("Default", 0, size);
int testHeight = getFontMetrics(font).getHeight();
if (testHeight < height && up != Boolean.FALSE) {
size++;
up = Boolean.TRUE;
} else if (testHeight > height && up != Boolean.TRUE) {
size--;
up = Boolean.FALSE;
} else {
break;
}
}
//At this point, size holds the optimal Vertical font size
//Now we will calculate the width of the sample string
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
FontMetrics fm = img.getGraphics().getFontMetrics(font);
int width = fm.stringWidth(testString);
//Using Martijn's answer, we calculate the optimal Horizontal font size
int newFontSize = size * textos[0].getWidth()/width;
//The perfect font size will be the minimum between both optimal font sizes.
//I have subtracted 2 from each font so that it is not too tight to the edges
return Math.min(newFontSize-2, size-2);
}
这篇关于最大化字体大小,同时将文本保留在JTextField中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!