Question

In a sub-class of JComponent I am overriding paintComponent method to draw. The first thing the overridden method does is to call super.paintComponent since most texts tell me to do this. Some say that this is necessary so that other JComponents can paint themselves. However, calling the super method clears the image, filling it with the background color. I don't want this happen. If I skip calling the super method, I am free to choose whether or not I want to call

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

in order to clear the image before redrawing.

But, I'm worried that by skipping the super method, I will be skipping other important operations the super method does. How can I make sure that those other important operations are executed while allowing myself to choose if I want to clear the image or not?

EDIT:

Here is my 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);
    }        
}

It just draws a line from where the user presses the mouse button to where the mouse was dragged to. If the mouse drags, the line moves. If the mouse is released it won't draw anything.

As it is, the program will erase the line the user is drawing if the mouse is released. I don't want the program to to that so that there will be a trail of lines.

Was it helpful?

Solution

You can safely skip the super() call or set opaque to false with JComponent's setOpague()

Good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top