我有一个JTextField,它的大小可能因分辨率而异。 JTextField将保存一个3个字母的字符串。最大化字体大小,同时保持文本在JTextField中
我想以这种方式设置JTextField的字体大小,使字体大小最大化,同时使JTextField中的文本FIT仍然完美。
有没有一个算法来做到这一点?
我有一个JTextField,它的大小可能因分辨率而异。 JTextField将保存一个3个字母的字符串。最大化字体大小,同时保持文本在JTextField中
我想以这种方式设置JTextField的字体大小,使字体大小最大化,同时使JTextField中的文本FIT仍然完美。
有没有一个算法来做到这一点?
我用的Martijn的答案,用下面的答案一起:
String length in pixels in Java
Java: Getting a font with a specific height in pixels
...为了写一个完整的回答我的问题。在这里。感谢所有贡献者。
您需要导入以下:
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);
}
使用'Toolkit.getDefaultToolkit()。getFontMetrics(font);'代替。 –
'JTextField#setColumns' – MadProgrammer
为什么? (15个字符) – kleopatra