小智 14
假设您需要带下划线和粗体的Serif样式字体,size = 12.
Map<TextAttribute, Integer> fontAttributes = new HashMap<TextAttribute, Integer>();
fontAttributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
Font boldUnderline = new Font("Serif",Font.BOLD, 12).deriveFont(fontAttributes);
Run Code Online (Sandbox Code Playgroud)
如果您不想加粗,请使用Font.PLAIN而不是Font.BOLD.不要使用Font类的getAttributes()方法.它会给你一个疯狂的通配符参数化类型Map<TextAttribute,?>,你将无法调用put()方法.有时Java会像那样令人讨厌.如果您对原因感兴趣,可以访问以下网站:http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html
coo*_*ird 13
查看Java API规范,看起来Font该类没有用于下划线的常量.
但是,使用Font(Map<? extends AttributedCharacterIterator.Attribute,?> attributes)构造函数,可以为其指定Map包含TextAttribute和要使用的值,以指定字体属性.(注意TextAttribute该类是其子类AttributedCharacterIterator.Attribute)
TextAttribute.UNDERLINE似乎TextAttribute是有趣的.
编辑:有一个使用Java教程TextAttribute中的使用文本属性到样式文本部分的示例.