Painting over the top of components in Swing?

2019-02-22 00:48发布

问题:

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.

回答1:

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.



回答2:

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



回答3:

hot really sure what do you really needed and final effect, maybe is there two another ways painting to

1) GlassPane

2) Viewport

you can put that together, carrefully Insets to the visible Rectanle



回答4:

Without seeing your actual code, it is difficult to say what you are doing wrong. However, I can still say what I would do:

Create a JPanel that represents the whole area where you want to draw, which — of course — contains every component.
Override that panel its paintComponents(Graphics) like this (EDITED, notice the s is now the last character from the method name):

@Override
public void paintComponents(Graphics g)
{ //                      ^
    super.paintComponents(g);

    // Draw your selection rectangle:
    g.setColor(Color.RED);
    g.drawRectangle(selectionRectangle); 
}


回答5:

Okay, this is what I've decided to do in the end:
I'm not sure if this is the best way to do it, but it seems to work okay.
Note: Using MigLayout.

In the constructor of the JPanel lying underneath the colored blocks.

 ...
 this.add(new JPanel() {

     @Override
     public boolean isOpaque() {
        return false;
     }

     @Override
     public void paintComponent(Graphics g) {
        if (dragShape != null) {
           g.setColor(Colors.SECONDARY);
           g.setStroke(new BasicStroke(2));
           g.draw(dragShape);
        }
     }
  }, "pos 0 0, width 100%, height 100%", 0);
  ...


回答6:

Custom painting on top of Swing components is facilitated by JLayeredPane. This article describes an abstract base class that facilitates overpainting specific areas (like selection rectangles or component bounds).