Search code examples
javaactionlistenervariable-initialization

java: ActionListener variable contains action to modify itself - 'Variable might not have been initialized'


I have a bit of code that does this:

  1. Creates an ActionListener

    a. Removes itself from the button that it will be attached to (see 2.)

    b. Does some other stuff

  2. Adds that ActionListener to a button

(in code:)

ActionListener playButtonActionListener = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent ae) {
        playButton.removeActionListener(playButtonActionListener);
        // does some other stuff
    }
};

playButton.addActionListener(playButtonActionListener);

On compilation, Java reports line 4 as an error (variable playButtonActionListener might not have been initialized) and refuses to compile. This is probably because playButtonActionListener is not technically initialized completely until the closing bracket, and the removeActionListener(playButtonActionListener) needs to happen after playButtonActionListener is initialized.

Is there any way to fix this? Do I have to completely change the way I am writing this block? Or is there some sort of @ flag or another solution?


Solution

  • Change

    playButton.removeActionListener(playButtonActionListener);
    

    with:

    playButton.removeActionListener(this);
    

    Since you're in the ActionListener anonymous class, this represents the current instance of the class.