简体   繁体   中英

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 .

The problem is that repaint() function is only executed after the variable boo has been set to true again. I have tried other methods like revalidate(), validate() but it didn't work. How should I fix my code?

This is an XY problem . You don't want to force JPanel to immediately repaint. 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.

So, the paintComponent() method of your extended JPanel would look like this:

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

where resetBoo() is a method which does boo = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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