简体   繁体   English

如何强制Jpanel立即用Java重新绘制?

[英]How can I force Jpanel to immediately repaint in Java?

Here is my code 这是我的代码

boolean boo = true;

ItemListener itemListener = new ItemListener() {
    public void itemStateChanged(ItemEvent event) {
        boo= false;         
        aSwingObj.repaint();
        boo = true;
     }
}

I want the repaint() method to run while boo is set to false, before it becomes true . 我希望在boo设置为false之前运行repaint()方法,然后将其变为true。

The problem is that repaint() function is only executed after the variable boo has been set to true again. 问题在于,仅在将变量boo再次设置为true后才执行repaint()函数。 I have tried other methods like revalidate(), validate() but it didn't work. 我尝试了其他方法,例如revalidate(),validate(),但没有用。 How should I fix my code? 我应该如何修正我的代码?

This is an XY problem . 这是一个XY问题 You don't want to force JPanel to immediately repaint. 您不想强迫JPanel立即重新绘制。 You want to enter a particular state immediately before painting begins and exit that state as soon as painting is over. 您想要在绘画开始之前立即进入特定状态,并在绘画结束后立即退出该状态。

One way of accomplishing that would in fact be to enter that state, force a repaint right on the spot, and then exit that state. 实际上,实现此目标的一种方法是进入该状态,当场强制重新粉刷,然后退出该状态。 But as you have seen, this is a bit hard to accomplish. 但是正如您所看到的,这有点难以实现。

So, another approach is to create a new class that does extend JPanel (or whatever the class of aSwingObj is) so that you can override the paintComponent() method and make it exit your special state once painting is done. 因此,另一种方法是创建一个新类,该类确实extend JPanel (或aSwingObj任何类),以便您可以重写paintComponent()方法,并在完成绘制后使其退出特殊状态。

So, the paintComponent() method of your extended JPanel would look like this: 因此,扩展的JPanelpaintComponent()方法如下所示:

 @Override
 public void paintComponent( Graphics g ) 
 {
        super.paintComponent( g );
        resetBoo();
 }

where resetBoo() is a method which does boo = true; 其中resetBoo()是执行boo = true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM