开发者

JPanel not repainting, even when calling repaint() and revalidate()

开发者 https://www.devze.com 2023-03-10 19:27 出处:网络
Hey guys. I have got a JPanel which changes color when it is clicked (this is handled correctly in another class).

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));
}
开发者_StackOverflow社区
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 newColor from a non-EDT thread, the Swing thread might never know the new value of currenBGColor. You could try making currentBGColor volatile.

Edit:

trying volatile was 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 use volatile but instead make sure that newColor is always called from the Swing event dispatch thread.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号