Repaint function messes up the whole frame

I have a problem when trying to draw some elements using paint method in Swing. As title says, my whole frame collapses and does some weird repeating.

I made a separate JPanel so I can manipulate drawn shapes:

public class PanelPovrsina extends JPanel{

private ArrayList<Oblik> listaOblika;

public PanelPovrsina() {    
    // svi oblici
    this.listaOblika = new ArrayList<Oblik>();
    this.listaOblika.add(new Kvadrat(new Tacka(50, 50), 50, "zuta", "crvena"));
    this.setBackground(Color.WHITE);
    this.setVisible(true);
}

public void paint(Graphics g) {
    if(this.listaOblika.isEmpty()) return; 
    Iterator<Oblik> it = this.listaOblika.iterator();
    while(it.hasNext()) {
        it.next().crtajUBoji(g);
    }
    repaint(); // this causes problems!
}

public ArrayList<Oblik> getListaOblika() {
    return this.listaOblika;
}

}

Here is the frame with this code:

enter image description here

And here it is without repaint method:

enter image description here

No, I know repaint method is essential in order to dynamically add shapes and actually draw, but I can't make this work correctly.

Also, as you can see from the code above, background of panel is set to white, but my frame would'n render it.

Hope there is enough information to solve my problem, if not, I will add code of my JFrame!

Thank you!

2 answers

  • answered 2018-01-14 10:34 Joe C

    You should never override the paint method, as it handles a number of other things behind the scenes. You should override paintComponent instead.

  • answered 2018-01-14 10:34 sebamed

    As @Joe C answered, I should have been using paintComponent method, not paint! Working code:

    public class PanelPovrsina extends JPanel{
    
    private ArrayList<Oblik> listaOblika;
    
    public PanelPovrsina() {
        // svi oblici
        this.listaOblika = new ArrayList<Oblik>();
        this.listaOblika.add(new Kvadrat(new Tacka(50, 50), 50, "zuta", "crvena"));
        this.setBackground(Color.PINK);
        this.setVisible(true);
    }
    
    
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Oblik obl : this.listaOblika) {
            obl.crtajUBoji(g);
        }
    
        repaint();
    }
    
    public ArrayList<Oblik> getListaOblika() {
        return this.listaOblika;
    }
    
    }