Hey guys. I have got a JPanel which changes color when it is clicked (this is handled correctly in another class).
Unfortunately, when I call the repaint() method, it doesn’t paint (or it calls the paintComponent method with the old Color value for var currentBGColor -> see code below)
public class MyClass extends JPanel {
curentBGColor = Color.red;
final int SIZE = 70;
public MyClass (){
setPreferredSize (new Dimension (SIZE,SIZE));
}
public void paintComponent (Graphics g)
{
g.setColor (currentBGColor); //I want this to paint white when newColor() is called
g.fillRect (0,0,getWidth(),getHeight());
g.setColor (Color.black);
g.drawLine (0,0,SIZE-1,0);
g.drawLine (0,0,0,SIZE-1);
g.drawLine (0,SIZE-1,SIZE-1,SIZE-1);
g.drawLine (SIZE-1,0,SIZE-1,SIZE-1);
}
void newColor (){
currentBGColor = Color.white;
repaint ();
revalidate();
}
}
Does anyone have any idea why it is not painting with the new color?
If you call
newColorfrom a non-EDT thread, the Swing thread might never know the new value ofcurrenBGColor. You could try makingcurrentBGColorvolatile.Edit:
trying
volatilewas meant as a debugging tool to see if it is a threading issue. If it is a threading issue, in order to follow the correct Swing threading model, you should not usevolatilebut instead make sure thatnewColoris always called from the Swing event dispatch thread.