【问题标题】:JPanel not repainting, even when calling repaint() and revalidate()JPanel 不重绘,即使调用 repaint() 和 revalidate()
【发布时间】:2011-09-08 22:00:22
【问题描述】:

大家好。我有一个 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();
}
}

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

【问题讨论】:

    标签: java colors jpanel paintcomponent


    【解决方案1】:

    如果您从非 EDT 线程调用 newColor,Swing 线程可能永远不会知道 currenBGColor 的新值。你可以尝试制作currentBGColorvolatile

    编辑:

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

    【讨论】:

    • 宾果游戏!我怎么没想到呢?
    • @Jimmy:不,volatile 在这里是非常错误的,只会让人感到困惑。只是不要这样做。是的,您应该在 EDT 上调用大多数摇摆调用,但我不知道线程是否是问题所在。我们需要看看你如何调用这个方法来帮助你纠正它,因为上面的代码没有显示错误,但请不要在这里按照 toto 的建议。我知道他的意思很好,但这完全是错误的。
    • 是的,我正要添加一条评论,指出这不是 Swing 方式。至少它可以识别问题。
    • @toto:我什至不会说它会那样做。据我们所知,他是可变阴影。
    • @toto:我强烈建议你删除这个答案——就是错了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    相关资源
    最近更新 更多