gpt4 book ai didi

Java:将 Text.Attribute 对象设置为其默认值时出现空指针异常,为什么?

转载 作者:行者123 更新时间:2023-12-01 14:13:05 25 4
gpt4 key购买 nike

因此,我正在使用不同的 TextAttribute 对象,并且它们的一些默认值是 null,例如 FOREGROUND(在 API 的 TextAttribute 部分中,它表示它们不同的键、值、主要常量和默认值)。在此代码中,我使用默认的 FOREGROUND,然后将其更改为 Color.BLUE,然后尝试将其更改为 API 中指定的默认值(null),但出现空指针异常?既然 null 是它的默认值,为什么会这样呢?这适用于所有默认值为 null 的 TextAttribute 对象,例如...FONT、CHAR_REPLACMENT、FOREGROUND、BACKGROUND、RUN_DIRECTION、INPUT_METHOD_HIGHLIGHT 和 NUMERIC_SHAPING...如果我更改该值,为什么不能在没有空指针异常的情况下将其更改回默认值? (我理解在示例中默认颜色是黑色,这不是我的问题,而是将对象设置为其定义的默认值,无一异常(exception))

public class NewClass extends Applet{
public void paint(Graphics g) {

Font font = new Font(Font.SERIF, Font.PLAIN, 24);
g.setFont(font);
String text = "This String";
g.drawString(text, 45, 30);

Hashtable<TextAttribute, Object> map =
new Hashtable<TextAttribute, Object>();

map.put(TextAttribute.FOREGROUND, Color.BLUE);
font = font.deriveFont(map);
g.setFont(font);
g.drawString(text, 45, 50);

map.put(TextAttribute.FOREGROUND, null);
font = font.deriveFont(map);
g.setFont(font);
g.drawString(text, 45, 70);
}

public static void main(String[] args) {

Frame f = new Frame("Attributed Text Sample");

f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

f.add("Center", new NewClass());
f.setSize(new Dimension(250, 200));
f.setVisible(true);
}

}

最佳答案

Hashtable 替换为 HashMap
Hashtable 不允许 null 值。因此您将收到 NullPointerException
根据javadocs

put()
Throws: NullPointerException - if the key or value is null.

请研究一下这些问题。
1.Why Hashtable does not allows null keys or values?
2.Differences between HashMap and Hashtable?

关于Java:将 Text.Attribute 对象设置为其默认值时出现空指针异常,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18343442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com