Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the generic Map for the font attributes be specified?

Tags:

java

generics

I have this method which jdk1.6 complains (no error just warning) about the generic type parameterizing is not used in the Map and ...:

public static Font getStrikethroughFont(String name, int properties, int size)
    {
        Font font = new Font(name, properties, size); 

        Map  attributes = font.getAttributes(); 
        attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); 
        Font newFont = new Font(attributes); 
        return newFont;             
    }

Then I changed to the following:

public static Font getStrikethroughFont2(String name, int properties, int size)
    {
        Font font = new Font(name, properties, size); 

        Map<TextAttribute, ?>  attributes = font.getAttributes(); 
        attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); 
        Font newFont = new Font(attributes); 
        return newFont;             
    }

but the

attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); 

statement is not valid anymore.

TextAttribute.STRIKETHROUGH_ON is a Boolean.

How can I use Generic Type feature in above method? I have looked at the Core Java book but didn't find an answer. Anybody can help me?

like image 774
5YrsLaterDBA Avatar asked Dec 13 '22 10:12

5YrsLaterDBA


1 Answers

What you should be using is font.deriveFont(map).

public static Font getStrikethroughFont2(String name, int properties, int size)
{
   Font font = new Font(name, properties, size); 
   Map<TextAttribute, Object>  attributes = new HashMap<TextAttribute, Object>();
   attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); 
   Font newFont = font.deriveFont(attributes);
   return newFont;             
}

This will solve your generics problem. The derive font will copy the old font, and then apply the attributes you supplied it. So, it will do the same thing you are trying to do using the Font constructor.

like image 182
jjnguy Avatar answered Mar 15 '23 23:03

jjnguy