我有这个方法,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
是 boolean 值。
如何在上述方法中使用通用类型功能?我看过 Core Java 这本书,但没有找到答案。任何人都可以帮助我吗?
最佳答案
你应该使用的是 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
构造函数执行的操作相同的操作。
关于java - 如何指定字体属性的通用映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7067901/