views:

3209

answers:

4

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

Font.BOLD bold font

Font.ITALIC italic font

What is the UNDERLINE font Constant ? I try all the available constants but it didn't work .

+1  A: 

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.

tvanfosson
A: 

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);
Markus Lausberg
+8  A: 

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.

coobird
+2  A: 

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

Blake