Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 690
rtheunissen Avatar asked Jan 08 '12 09:01

rtheunissen


2 Answers

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.

like image 140
camickr Avatar answered Oct 20 '22 18:10

camickr


Use a Layered Pane:

http://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html

This allows you to create overlapping components.

Use a glass pane to handle the drag painting, and possibly events as well:

http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html#glasspane

like image 42
The Nail Avatar answered Oct 20 '22 18:10

The Nail