How to specify a common map for font attributes?

I have this method that complains to jdk1.6 (without warning of an error) about parameterization of a generic type is not used in 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

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

not valid.

TextAttribute.STRIKETHROUGH_ON is a boolean.

How can I use the Generic Type function in the method described above? I looked at the Core Java book, but could not find an answer. Can anybody help me?

+4
source share
3 answers

What you should use 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 generic problem. The font output will copy the old font, and then apply the attributes that you provided to it. This way it will do the same thing you are trying to do using the Font constructor.

+8
source

You cannot put on this card. It is read-only.

Map that you can use to place attributes, Map<String, Object>

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

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

Not sure I understood this question well, but what about this:

 Map<TextAttribute, Object> 

Each object has an object as a superclass, and you still cannot put any primitive types in Map. So, with Object, you get everything!

0
source

All Articles