删除/清除Graphics#fillRect()绘制的矩形

时间:2011-03-19 17:51:19

标签: java swing

我已经将它绘制成条形图,但是当我重绘()时,新图表将绘制在前一个图表之上。使用新阵列重新绘制几次后,它看起来像this如何清除或删除绘制的条形图?

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);
        }
    }

}

2 个答案:

答案 0 :(得分:3)

如果面板不透明(通常是默认情况下),那么您可以使用背景颜色填充组件:

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

答案 1 :(得分:2)

也许你可以打电话

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

paintComponent()方法中的第一件事。