简体   繁体   中英

Override setText() method in JLabel

I have the following code implemented in Java.

public class FadeLabel extends javax.swing.JLabel {

    private Timer onTimer;

    public FadeLabel() {
        init();
    }

    private void init(){
        setHorizontalAlignment(CENTER);
        setVerticalAlignment(CENTER);
        onTimer = new Timer(100, (ActionEvent e) -> {
            // animation code
        });
    }

    @Override
    public void setText(String text) {
        onTimer.start();
        super.setText(text);
    }
}

When I create an object of this class, it gives a NullPointerException in the setText() method, the line onTimer.start() .

I want to know why is this exception happening..?

ps: I know what is a NullPointerException is. I want to know how is it generated here..

This is how I instantiate.

notificationLabel = new FadeLabel();

Looking at the source code for JLabel

public JLabel() {
    this("", null, LEADING);
}

public JLabel(String text, Icon icon, int horizontalAlignment) {
    setText(text);
    setIcon(icon);
    setHorizontalAlignment(horizontalAlignment);
    updateUI();
    setAlignmentX(LEFT_ALIGNMENT);
}

Thus we can see that the no-argument constructor calls the other one, which then calls setText . However at that point your init method hasn't run, so onTimer is still NULL .

You define the property onTimer. You have a method init. You must call it to instantiate the timer property onTimer.

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