0

大家好。我有一个 JPanel,它在单击时会改变颜色(这在另一个类中得到了正确处理)。

不幸的是,当我调用 repaint() 方法时,它不会绘制(或者它使用 var currentBGColor 的旧 Color 值调用 paintComponent 方法 -> 请参见下面的代码)

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();
}
}

有谁知道为什么它没有用新颜色绘画?

4

1 回答 1

1

如果您newColor从非 EDT 线程调用,Swing 线程可能永远不会知道currenBGColor. 你可以尝试制作currentBGColor volatile.

编辑:

尝试volatile是作为调试工具来查看它是否是线程问题。如果是线程问题,为了遵循正确的 Swing 线程模型,您不应该使用volatile而是确保newColor始终从 Swing 事件调度线程调用它。

于 2011-06-05T21:46:14.203 回答