开发者

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

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 bo开发者_Go百科ok but didn't find an answer. Anybody can help me?


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.


You can't put in that map. It is meant just for reading.

The map you can use to put attributes is Map<String, Object>

If you need to get the existing map and create a font with its attributes + additional ones, use:

Map<TextAttribute, Object> map = 
   new HashMap<TextAttribute, Object>(font.getAttributes());


Not sure I've understood the question well but how about doing this:

Map<TextAttribute, Object>

Every object has Object as Superclass and you anyway can't put any primitive types in a Map. So with Object, you get everything !

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜