我想在 componentResized 事件上设置按钮的字体大小。我得到了屏幕尺寸和按钮的大小。但无法找到计算要设置的首选字体大小的方法。如果按钮的宽度增加/减少,字体大小也应相应增加/减少。我也无法获得 Graphics 对象。
有什么办法可以解决这个问题?
最佳答案
这更多的是暴力解决方案。
1)您可以尝试通过执行以下操作来获取字体规范:
// get metrics from the graphics
FontMetrics metrics = graphics.getFontMetrics(font);
// get the height of a line of text in this font and render context
int hgt = metrics.getHeight();
// get the advance of my text in this font and render context
int adv = metrics.stringWidth(text);
// calculate the size of a box to hold the text with some padding.
Dimension size = new Dimension(adv+2, hgt+2);
2) 然后您可以搜索适合您的组件的字体大小。
Font savedFont = oldFont;
for (int i = 0; i < 100; i++) {
Font newFont = new Font(oldFont.getFontName(), oldFont.getStyle(), i);
Dimension d = getFontSize(g,newFont,text);
if(componentSize.height < d.height || componentSize.width < d.width){
return savedFont;
}
savedFont = newFont;
}
将它们放在一起(注意这未经测试)
public Dimension getFontSize(Graphics graphics, Font font, String text){
// get metrics from the graphics
FontMetrics metrics = graphics.getFontMetrics(font);
// get the height of a line of text in this font and render context
int hgt = metrics.getHeight();
// get the advance of my text in this font and render context
int adv = metrics.stringWidth(text);
// calculate the size of a box to hold the text with some padding.
Dimension size = new Dimension(adv+2, hgt+2);
return size;
}
public Font findFont(Dimension componentSize, Font oldFont, String text, Graphics g){
//search up to 100
Font savedFont = oldFont;
for (int i = 0; i < 100; i++) {
Font newFont = new Font(oldFont.getFontName(), oldFont.getStyle(), i);
Dimension d = getFontSize(g,newFont,text);
if(componentSize.height < d.height || componentSize.width < d.width){
return savedFont;
}
savedFont = newFont;
}
return oldFont;
}
使用组件编辑以获取 FontMetrics
public Dimension getFontSize(FontMetrics metrics ,Font font, String text){
// get the height of a line of text in this font and render context
int hgt = metrics.getHeight();
// get the advance of my text in this font and render context
int adv = metrics.stringWidth(text);
// calculate the size of a box to hold the text with some padding.
Dimension size = new Dimension(adv+2, hgt+2);
return size;
}
public Font findFont(Component component, Dimension componentSize, Font oldFont, String text){
//search up to 100
Font savedFont = oldFont;
for (int i = 0; i < 100; i++) {
Font newFont = new Font(oldFont.getFontName(), oldFont.getStyle(), i);
Dimension d = getFontSize(component.getFontMetrics(newFont),newFont,text);
if(componentSize.height < d.height || componentSize.width < d.width){
return savedFont;
}
savedFont = newFont;
}
return oldFont;
}
关于java - Swing 缩放组件的文本字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8183949/