Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redundant Condition

Tags:

java

timer

swing

I have a problem in this block of code that I saw in oracles site. Can someone explain it for me?

Action updateCursorAction = new AbstractAction() {
    boolean shouldDraw = false;
    public void actionPerformed(ActionEvent e) {
        if (shouldDraw = !shouldDraw) { // <----- here is my problem, what's this condition for? 
                                       // isn't it always false?
            drawCursor();
        } else {
            eraseCursor();
        }
    }
};

new Timer(300, updateCursorAction).start();
like image 633
Moh Mah Avatar asked May 29 '11 01:05

Moh Mah


1 Answers

if (shouldDraw = !shouldDraw)

That is not doing if(shouldDraw != shoundDraw). I think that's what's confusing you. It is instead doing a negation on shouldDraw and checking to see what the result was.

So, the functionality is that if shouldDraw was ever false going into that condition, it will be set to true, and the if block will execute. If shouldDraw went into the condition as true, it will get negated, and the else block will be executed.

This will essentially toggle shouldDraw between true and false on every execution of the ActionListener which will make the cursor flash.

like image 57
jjnguy Avatar answered Oct 09 '22 06:10

jjnguy