Search code examples
javaswingpaintpaintcomponent

Why not to draw directly inside JFrame


Can anyone explain me why shouldn't i use paint method to draw directly inside a JFrame window, and i should use paintComponent method with a JPanel inside the JFrame ?

Thanks in advance.


Solution

  • Three main reasons...

    1. Top level containers aren't double buffered, which cause flickering when the frame is repainted, yes, you can implement you're own double buffering, but...
    2. Painting inside a frame does not take into consideration the frames borders, meaning that it's possible to paint under them. Frame borders are also platform/look and feel specific, meaning that there sizes change
    3. In the case of Swing windows, there are components that already exist on the window, meaning that they paint over (or be painted over), in most cases, both (because of the optimised painting engine in Swing), making it difficult to produce a reasonable result

    For point #2, frame decorations are painted WITHIN the "window" bounds, not outside them

    Take a look at...

    for more details

    Make the time to read through Painting in AWT and Swing and Performing Custom Painting for more details