What is the Constant Value of the Underline font in Java?

梦想与她 提交于 2019-11-29 09:29:57

Looking at the Java API Specification, it appears that the Font class does not have a constant for underlining.

However, using the Font(Map<? extends AttributedCharacterIterator.Attribute,?> attributes) constructor, one can give it a Map containing the TextAttribute and the value to use, in order to specify the font attributes. (Note that the TextAttribute class is a subclass of AttributedCharacterIterator.Attribute)

TextAttribute.UNDERLINE seems like the TextAttribute of interest.

Edit: There's an example of using TextAttribute in the Using Text Attributes to Style Text section from The Java Tutorials.

Suppose you wanted a underlined and bolded Serif style font, 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);

If you don't want it bolded, use Font.PLAIN instead of Font.BOLD. Don't use the getAttributes() method of the Font class. It will give you a crazy wildcard parameterized type Map<TextAttribute,?>, and you won't be able to invoke the put() method. Sometimes Java can be yucky like that. If you're interested in why, you can check out this site: http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html

Underlining is not a property of the font but of the text segment. When rendered the text is rendered in the font specified then a line is drawn under it. Depending on what framework you are using, this may be done for you using properties or you may have to do it yourself.

For SWT you can use:

StyledText text = new StyledText(shell, SWT.BORDER);
text.setText("0123456789 ABCDEFGHIJKLM NOPQRSTUVWXYZ");
// make 0123456789 appear underlined
StyleRange style1 = new StyleRange();
style1.start = 0;
style1.length = 10;
style1.underline = true;
text.setStyleRange(style1);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!