Search code examples
javaswingrepaintpaintcomponent

Understanding Swing and repaint()


I am trying to understand how painting with Swing works. For that purpose I've been reading the Oracle tutorial: http://docs.oracle.com/javase/tutorial/uiswing/painting/step3.html

My question is a simple one: Why do the two calls to the same function (repaint) have different behaviour? How does it come that the UI Delegate paints the background on the previously painted rectangle, but paints a new rectangle on the new area? I don't see any particular reason on paintComponent() for that.

I have also read http://docs.oracle.com/javase/tutorial/uiswing/painting/closer.html trying to understand the situation. It seems there is some connection to the opaque property of a component. Does this property change after we create a new rectangle, so that it is true (thus, as mentioned, the ui.update() will set it to the background color). How come it paintComponent() doesn't paint a new rectangle there?


Solution

  • The function is called with different parameters:

    repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
    squareX=x;
    squareY=y;
    repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
    

    In the first call to repaint() squareX and squareY indicates location of the previously painted object. In second the second call, squareX and squareY is changed to the current mouse location.

    From JComponent API documentation on repaint():

    Adds the specified region to the dirty region list if the component is showing. The component will be repainted after all of the currently pending events have been dispatched.

    That is, the first call to repaint() marks the previous location as dirty, the second, marks the current location as dirty. When the event (moveSquare) is completed, paintComponent is re-executed, and these two areas are updated. The red rectangle is only placed in the new location, the old location is updated to be "empty".