Question

I painted some figures using paintComponent() method:

public void paintComponent(Graphics g){

        super.paintComponent(g);
        g.setColor(Color.BLUE);

        g.drawRect(50, 50, 50, 50);
        g.drawOval(60, 60, 60, 60);

        //repaint();
        //g.drawOval(10, 10, 10, 10); - nothing effect
}

But now I want to erase all these figures and paint some new figure. I don't know how i must do it? Maybe I must use repaint() method but use it wrong?

Was it helpful?

Solution

Whatever you are writing in the paintComponent method will be painted each time that the method is called. Based on the description so far, the usual way of achieving what you want to achieve is to determine whether something should be painted or not:

class TheClass extends JComponent
{
    private boolean paintTheFirstThing = true;

    @Override
    protected void paintComponent(Graphics g){
        super.paintComponent(g);

        if (paintTheFirstThing)
        {
            g.setColor(Color.BLUE);
            g.drawRect(50, 50, 50, 50);
            g.drawOval(60, 60, 60, 60);
        }
        else
        {
            g.drawOval(10, 10, 10, 10)  
        }
    }

    void setPaintTheFirstThing(boolean p)
    {
        this.paintTheFirstThing = p;
        repaint();
    }
}

(This is only a sketch, showing the basic idea. Of course, when you want to paint many different things, you'll not create lots of boolean flags for them. The key point is that in your paintComponent method, you have to describe what should be painted at certain point in time)

OTHER TIPS

Java draws all the figures your describe in the paintComponent(), but only when this method returns. So you can't draw then hide some figures in this method for the same method call. This method needs to be called a first time with a set of figures to show, then another time with another set of figures.

Maybe something like:

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLUE);

    if (drawFiguresX) {
        g.drawRect(50, 50, 50, 50);
        g.drawOval(60, 60, 60, 60);
    } else {
        g.drawOval(10, 10, 10, 10);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top