java 如何将字体设置为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29422800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:14:31  来源:igfitidea点击:

How to set fonts to a string

javastringgraphicsfontsdraw

提问by Ski

Is there a way to set fonts on a string, and then draw the string using graphics? I know you can do it on Jlabels, and Jtextfields, and J-other components, but is there a way to do it just on the string instead? Thank you.

有没有办法在字符串上设置字体,然后使用图形绘制字符串?我知道您可以在 Jlabels、Jtextfields 和 J-other 组件上执行此操作,但是有没有办法仅在字符串上执行此操作?谢谢你。

回答by bucmipid-153

You can do it with attributed stringsan example of is

你可以用属性字符串来做一个例子是

Font font = new Font("LucidaSans", Font.PLAIN, 14);
AttributedString atString= new AttributedString("Example text string");
atString.addAttribute(TextAttribute.FONT, font);
graphic.drawString(atString.getIterator(),x,y);

Cheers!

干杯!

回答by Ski

We can actually set the font in graphics...and then draw the string.

我们实际上可以在图形中设置字体...然后绘制字符串。

public void paintComponent(Graphics g) {

    super.paintComponent(g);

    g.setColor(Color.BLUE);
    g.setFont(Fonts.f);
    g.drawString(Fonts.text, 50, 50);

}

回答by MadProgrammer

Yes, it's possible, start by checking out the Graphics, Text tutorials

是的,这是可能的,首先查看图形、文本教程

Basically, you can set the font using Graphics#setFontand draw a Stringusing Graphics#drawString.

基本上,您可以设置字体 usingGraphics#setFont并绘制Stringusing Graphics#drawString

Also see Performing Custom Paintingfor how you can perform custom painting in Swing

另请参阅执行自定义绘画以了解如何在 Swing 中执行自定义绘画

For example

对于例如

List available font names....

列出可用的字体名称....

String fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
for (String font : fonts) {
    System.out.println(font);
}

or

或者

Font fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
for (Font font : fonts) {
    System.out.println(font);
}

You can manipulate a font's properties using one of the Font#derivemethods...

您可以使用以下Font#derive方法之一操作字体的属性...

 Font font = ...;
 Font bigger = font.derive(32f);
 Font bolder = font.derive(Font.BOLD);
 Font biggerAndBolder = font.derive(Font.BOLD, 32f);