Question

I'm trying to make a paint in java, with classes and hierarchy. But my paint area isn't getting the background color (defined as white) and when i click it makes a print screen in the jpanel area of drawing. With super.paintComponent(g) the interface appears all right but i only get one point of each time. With super.paintComponents(g) it prints the frame in the jpanel area.

any thoughts about what's happen?

public class MandaDesenhar extends JPanel
{
static int x;
static int y;

private static final long serialVersionUID = 1L;
int i = 0;

public void paintComponent(Graphics g)
{   
    super.paintComponents(g);

    if (Paint4Fun.lista.size() == 0)
        return;

    while (i<Paint4Fun.lista.size())
    {
        FormaPrimitiva forma = Paint4Fun.lista.get(i);
        forma.desenha(g);
        i++;
    }
}
Was it helpful?

Solution

You should define i locally in your paintComponent method, not outside of it, and initialize it there to 0.

Otherwise you are always only painting the new elements of your list, not the older ones.

Edit: You can write your loop better as a for-loop:

for(int i = 0; i < Paint4Fun.lista.size(); i++) {
   FormaPrimitiva forma = Paint4Fun.lista.get(i);
   forma.desenha(g); 
}

or even more clearly:

for(FormaPrimitiva forma : Paint4Fun.lista) {
    forma.desenha(g);
}

Generally, always declare variables (like the i here) in the smallest possible scope (the method or even the loop, here).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top