-3

I am trying to make a do not disturb feature for my notification in the system tray and I am trying to make an if statement that goes if variable dnd = false then change the system tray name to "Do Not Disturb - on" and set dnd to true else set dnd = false but under the dnd = true; and dnd = false; it has a red line and says "Local variable dnd defined in an enclosing scope must be final or effectively final" and I am not sure what to do. Please help.
Here my code:

boolean dnd = false;
doNotDisturb.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {  
        if (dnd == false) {
            dnd = true;
            doNotDisturb.setName("Do Not Disturb - on");
        } else {
            dnd = false;
        }
    }
});
vinS
  • 1,417
  • 5
  • 24
  • 37
Floffah
  • 3
  • 5
  • Solution depends on what you really want do. You can't *reassign* new value to local variable declared outside of anonymous class. So you could try to move that variable to anonymous class, or make it field of upper class, or instead of using boolean wrap it in other type and change its state (by getters and setters). – Pshemo Dec 17 '17 at 16:01
  • Did you search on the error message? Please do this *before* asking. – Hovercraft Full Of Eels Dec 17 '17 at 16:02

1 Answers1

0

The variable dnd must be final or effectively final (this is the case). This is why you're able to reference it from a closure context. The compiler doesn't want you to reassign dnd from within the closure or anonymous class.

You can solve the problem by either

  1. Wrapping dnd in an object:

    DndConfig dndConfig = new DndConfig();

    and in the anonymous class:

    dndConfig.dnd = true; //your logic

  2. Making dnd an instance field of the main class.

Floffah
  • 3
  • 5
ernest_k
  • 44,416
  • 5
  • 53
  • 99