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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With