Search code examples
javaswingjpanelpaintcomponentmiglayout

Painting over the top of components in Swing?


I have a JPanel added to a JViewport, and the panel has several other panels added to it. I'm trying to implement a dragging selection, where you can select more than one component by dragging the mouse. The only problem I'm facing is that the selection rectangle is being painted behind the components added to the main JPanel. How can I paint over the top of them?

My structure is as follows:
JFrame -> ContentPane -> JLayeredPane -> JScrollPane -> JPanel -> JPanel [].

Design draft for college assignment:
As you can see, the rectangle is behind the other panels.

Design draft for college assignment.


Solution

  • This is what I'm already doing (on a much simpler level obviously), and Swing paints the rectangle underneath the components added to it.

    This is one case where you should override the paint() method of the panel and not the paintComponent() method. Then the custom painting will be done AFTER all the child components have been painted.