Search code examples
javaswingjlabeljava-2d

JLabel not showing when called in paint method


I have the following code:

public class Canvas extends JPanel{
 JLabel label = new JLabel();
 public void init()
    {
        label.setSize(100, 100);
        label.setLocation(10, 10);
        label.setText("lalallaalal");
        this.add(label);
    }
@Override
public void paint(Graphics g) {
        super.paint(g);

                paintRoad(g);
                paintBorders(g);

                paintEnemies(g, enemies);
                paintPlayer(g);
    }

I want the label to be redrawn every time the JPanel is repainted, but when I put this.add(label) at the end of paint method it doesn't show the label. Any idea why?


Solution

  • paint() invokes paintComponent(). It's better to override paintComponent instead of paint.

    protected void paintComponent(Graphics g)
    

    A Closer Look at the Paint Mechanism