Search code examples
javaswingjframejpanelpaint

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!


Solution

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