0

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


    }
}
andrewJames
  • 19,570
  • 8
  • 19
  • 51
sottaceto
  • 3
  • 2
  • You should be overriding `paintComponent` but we need to see your code – g00se Apr 24 '22 at 12:20
  • 1
    Did you read [Swing’s Threading Policy](https://docs.oracle.com/en/java/javase/17/docs/api/java.desktop/javax/swing/package-summary.html#threading)? Don’t modify the UI from a background thread. Use `javax.swing.Timer` to perform a UI action repeatedly. – Holger May 03 '22 at 14:45

1 Answers1

0

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).

David Weber
  • 173
  • 9