简体   繁体   中英

Java: Null Pointer exception while setting a Text.Attribute Object to it's default value, why?

So I am working with different TextAttribute objects and some of their default values are null, like FOREGROUND (In the TextAttribute part of the API it says their different keys, values, Pricipal Constants and Default Values). In this code I use the default FOREGROUND, then change it to Color.BLUE, then try to change it to its Default Value that is specified in the API which is null, but I get a null pointer exception? Why is that since null is it's default value? This is for all TextAttribute objects with a default value null, like... FONT, CHAR_REPLACEMENT, FOREGROUND, BACKGROUND, RUN_DIRECTION, INPUT_METHOD_HIGHLIGHT, and, NUMERIC_SHAPING....If I change the value why can't I change it back to default without a null pointer exception? (I understand in the example the default color is black, that is not my question, it is about setting the object to its defined default value without an 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);
}

}

Replace your Hashtable with HashMap .
Hashtable do not allow null value.So you are getting NullPointerException .
According to java docs

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

Please have look into these SO Questions.
1. Why Hashtable does not allows null keys or values?
2. Differences between HashMap and Hashtable?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM