如何使文本字体缩小并匹配JTextArea高度?
答
使用以下方法,(更新最大,并根据您的要求最小尺寸的)
public static int getMatchingFontSize(JComponent comp, String string) {
int minSize = 10;
int maxSize = 60;
Dimension size = comp.getSize();
if (comp == null || comp.getFont() == null || string.isEmpty()) {
return -1;
}
//Init variables
int width = size.width;
int height = size.height;
Font font = comp.getFont();
int curSize = font.getSize();
FontMetrics fm = comp.getFontMetrics(new Font(font.getName(), font.getStyle(), maxSize));
while (fm.stringWidth(string) + 4 > width || fm.getHeight() > height) {
maxSize--;
fm = comp.getFontMetrics(new Font(font.getName(), font.getStyle(), maxSize));
curSize = maxSize;
}
while (fm.stringWidth(string) + 4 < width || fm.getHeight() < height) {
minSize++;
fm = comp.getFontMetrics(new Font(font.getName(), font.getStyle(), minSize));
curSize = minSize;
}
if (curSize < minSize) {
curSize = minSize;
}
if (curSize > maxSize) {
curSize = maxSize;
}
return curSize;
}
找'java.awt.FontMetrics'类,它会做的工作。 – aKilleR
*“,但问题是当文本太长,它不适合和滚动条出现”*这是一个功能,而不是一个问题。 –