简体   繁体   中英

Jlabels flickering or randomly not showing

I have a problem with a Java 2d game I'm developing.

Some of the game screen elements are drawn in a Jpanel overriding the paint() method and some other elements are Jlabels added to that panel.

The problem is that the elements drawn in the paint() method are always up to date (I recall a Jpanel.repaint() every 30ms from a thread) but the Jlabels often are not shown or are blinking in a random way.

I've searched a lot but couldn't find a way to update all the elements at the same time.

This is the core structure of the code:

Main Class

final class ATC_sim {
 
    // ...

    public CustomLabel[] label; 
    // CustomLabel is just a class in which are organized differents JLabels in
    // a certain relative position.  

    // ...
    
    private ATC_sim(){
        initGui();
        initGame();
    }

    private void initGui(){
        frame = new JFrame();
        pGame = new GamePanel(this);
        for(int i=0; i< label.length; i++){
            pGame.add(label[i]);
        }
        frame.add(pGame);
        // ...
    }

    private void initGame(){
        loop = new Loop(this, 30);                  
        thread = new Thread(loop);
        thread.start();
        
        pGame.repaint();
    }

    // method recalled every 30ms from thread(loop)
    public void updateGame(){         
        // do the math of the game (in which I also move the position of labels)
        // ...
        for(int i=0; i< label.length; i++){
            label[i].update(); // this method update text in Jlabels and position of label.
        }


        pGame.repaint();
    }
}

GamePanel class

public class GamePanel extends JPanel {
    // ...

    public GamePanel(ATC_sim a) {
        this.atc = a;
        // ...
    }
    
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        
        // do some drawings according to some variable calculated in updateGame()


    }
}

At first, if you want better performance and a lower chance of lagging/stuttering, use paintImmediately() instead of repaint() .

It could be, that this solves your problem already.

The second part is: Do you use double buffering? If you use this, this problem will definitely disappear (in my oppinion).

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