简体   繁体   English

如何在 Java SWING 中设置自定义字体的大小和其他属性(粗体、斜体等)

[英]How to set a custom font's size and other attributes (bold, italic, etc) in Java SWING

Usually, when I initialize the fonts I want to use in my SWING applications, I do it this way:通常,当我初始化要在我的 SWING 应用程序中使用的 fonts 时,我会这样做:

public static final Font TITLEFONT = new Font("Calibri", Font.BOLD, 40);

Now, I have to do it a bit differently since I'm using some custom fonts from a.ttf file.现在,我必须做一些不同的事情,因为我使用的是来自 a.ttf 文件的一些自定义 fonts。 I initialize the font this way:我这样初始化字体:

try
{
    InputStream is = OptionsValues.class.getResourceAsStream("fonts//KOMIKAX_.ttf");
    TITLEFONT = Font.createFont(Font.TRUETYPE_FONT, is);
}
catch (Exception ex)
{
    ex.printStackTrace();
    System.err.println("Font not loaded.  Using Calibri font.");
    TITLEFONT = new Font("Calibri", Font.BOLD, 40);
}

I'm pretty sure it initializes it correctly (I can't tell for sure since it is too small for me to see), but I'd like to know how I can manually set the font's size (and if it's bold / other attributes) when loading a font this way.我很确定它会正确初始化它(我不能确定,因为它太小了,我看不到),但我想知道如何手动设置字体的大小(如果它是粗体/其他属性)以这种方式加载字体时。

Thanks a lot in advance!非常感谢!

createFont returns a Font and you can call deriveFont(...) on this, passing in a float for the point size, or an int and float for Font style and point size. createFont返回一个Font,您可以在其上调用deriveFont(...) ,为点大小传递一个浮点数,或者为Font样式和点大小传递一个int和float。 I cannot say whether it will work for your particular situation, but it's worth a try. 我不能说它是否适合你的特殊情况,但值得一试。

eg, 例如,

InputStream is = OptionsValues.class.getResourceAsStream("fonts//KOMIKAX_.ttf");
TITLEFONT = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(Font.BOLD, 40f);

I'd simply use:我会简单地使用:

Font.ITALIC字体.ITALIC

Font.BOLD字体.BOLD

Font.PLAIN字体.PLAIN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM