Reputation:
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
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
Reputation: 108947
maybe you can call
g.clearRect(0, 0, getWidth(), getHeight() );
first thing in your paintComponent()
method.
Upvotes: 2