user479911
user479911

Reputation:

Remove/clear rectangles drawn by Graphics#fillRect()

I've made this to draw bar graphs, but when I do repaint() the new chart is drawn on top of the previous one. After a few repaints with new arrays it looks like this. How can I clear or remove drawn bars?

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class BarChart extends JPanel {

    private int[] array;

    public BarChart(int[] array) {
        this.array = array;
    }

    public int[] getArray() {
        return array;
    }

    public void setArray(int[] array) {
        this.array = array;
    }

    @Override
    protected void paintComponent(Graphics g) {
        //Determine longest bar
        int max = Integer.MIN_VALUE;
        for (Integer value : array) {
            max = Math.max(max, value);
        }
        //Paint bars
        int width = (getWidth() / array.length) - 2;
        int x = 1;
        for (Integer value : array) {
            int height = (int) ((getHeight() - 5) * ((double) value / max));
            g.setColor(Color.blue);
            g.fillRect(x, getHeight() - height, width, height);
            g.setColor(Color.black);
            g.drawRect(x, getHeight() - height, width, height);
            x += (width + 2);
        }
    }

}

Upvotes: 0

Views: 26195

Answers (2)

Russ Hayward
Russ Hayward

Reputation: 5667

If the panel is opaque (they usually are by default), then you can do this to fill the component with the background colour:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    // Your code here
}

Upvotes: 3

Bala R
Bala R

Reputation: 108947

maybe you can call

g.clearRect(0, 0, getWidth(), getHeight() );

first thing in your paintComponent() method.

Upvotes: 2

Related Questions