我有这个方法,jdk1.6报告(没有错误,只是警告)泛型类型参数化没有在Map中使用,并且...:
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;
}然后我改成了以下代码:
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;
}但是
attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); 语句不再有效。
TextAttribute.STRIKETHROUGH_ON是一个布尔值。
如何在上述方法中使用泛型功能?我看过Core Java这本书,但没有找到答案。有人能帮我吗?
发布于 2011-08-16 00:57:49
您应该使用的是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;
}这将解决您的泛型问题。派生字体将复制旧字体,然后应用您为其提供的属性。因此,它将执行您尝试使用Font构造函数执行的相同操作。
发布于 2011-08-16 00:56:10
你不能在那个地图上使用put。这只是为了阅读。
可用于放置属性的地图是Map<String, Object>
如果您需要获取现有的映射并创建一个包含其属性和其他属性的字体,请使用:
Map<TextAttribute, Object> map =
new HashMap<TextAttribute, Object>(font.getAttributes());发布于 2011-08-16 00:55:47
我不确定我已经很好地理解了这个问题,但是这样做如何:
Map<TextAttribute, Object>每个对象都有作为超类的对象,而且无论如何都不能将任何原语类型放在Map中。所以有了Object,你就能得到一切!
https://stackoverflow.com/questions/7067901
复制相似问题