防止super.paintComponent调用clearRect

时间:2012-03-04 00:16:26

标签: java swing background clear jcomponent

JComponent的子类中,我正在覆盖paintComponent方法。被覆盖的方法所做的第一件事是调用super.paintComponent,因为大多数文本告诉我这样做。有人说这是必要的,以便其他JComponents可以自己画画。但是,调用super方法会清除图像,并使用背景颜色填充图像。我不希望这种情况发生。如果我跳过调用超级方法,我可以自由选择是否要调用

g.setColor(getBackground());
g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);

为了在重绘之前清除图像。

但是,我担心通过跳过super方法,我将跳过super方法所做的其他重要操作。如何确保执行其他重要操作,同时允许自己选择是否要清除图像?

编辑:

这是我的paintComponent:

public void paintComponent(Graphics g) {
    super.paintComponent(g); // necessary so other panels can paint themselves.    
    //         g.setColor(getBackground());
    //         g.fillRect(0, 0, getWidth(), getHeight());
    //         g.setColor(Color.black);
    if (down) {
        g.drawLine(downX, downY, currentX, currentY);
    }        
}

它只是绘制一条线,用户按下鼠标按钮到鼠标拖动的位置。如果鼠标拖动,则线条会移动。如果鼠标被释放,它将不会绘制任何东西。

实际上,如果释放鼠标,程序将擦除用户正在绘制的线条。我不希望程序这样,以便有一条线。

1 个答案:

答案 0 :(得分:-1)

您可以安全地跳过super()调用或使用JComponent's setOpague()

将opaque设置为false 祝你好运!