Argh I give up.. can someone help me feel really dumb by saying what I'm doing wrong?
In Java, I just wanna have a flashing rectangle appear and disappear every visible moment, using JPanel.
Code:
public void paintComponent(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
try {
Thread.sleep(100);
} catch (Exception e) {
}
g.setColor(Color.red);
g.fillRect(0, 0, 50, 50);
}
I have a for loop in main where I call repaint() . What happens is starts with full white, then changes to red without keeping the white background, then stays that way. I print a statement to console every loop instance outside of the repaint(), and it prints them WAY faster than the sleep() should be allowing (I checked and the sleep doesn't throw any exceptions.. even with a sleep of a few second, it prints them like crazy). No clue what's going on.
Edit: If I remove the sleep, it keeps the white background when drawing the red rectangle. Freaking sleep(), man. What the hell.
So I guess I solve that by adding another full white recolor after the sleep.. but that doesn't fix the main problem.
Edit 2: okay there has to be something fundamental about swing I'm not getting. Is it just not being "thread safe" that's messing me up? It's still wrong even when I remove the sleep though..